<?php
session_start();
// login_google.php

header('Content-Type: application/json');
include 'koneksi.php';
include 'send_admin_email.php'; // <- Tambahkan ini agar bisa kirim email

$data = json_decode(file_get_contents('php://input'), true);
$email = $data['email'];
$name = $data['name'];
$uid = $data['uid'];
$photo = $data['photo'];

// Cek apakah user sudah ada
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE email = ?");
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if ($row = mysqli_fetch_assoc($result)) {
    // Jika user sudah ada, update foto jika belum ada
    if (empty($row['photo_url']) && !empty($photo)) {
        $stmtUpdate = mysqli_prepare($conn, "UPDATE users SET photo_url = ? WHERE email = ?");
        mysqli_stmt_bind_param($stmtUpdate, "ss", $photo, $email);
        mysqli_stmt_execute($stmtUpdate);
    }

    // Pastikan akun sudah diverifikasi
    if ($row['is_verified'] != 1) {
        echo json_encode(['status' => 'error', 'message' => 'Akun belum diverifikasi admin.']);
        exit;
    }

    session_start();
    $_SESSION['session_username'] = $email;
    $_SESSION['session_name'] = $row['username'];
    $_SESSION['session_photo'] = $row['photo_url'];
    echo json_encode(['status' => 'success']);
} else {
    // Insert akun baru dari Google (dengan status belum terverifikasi)
    $stmtInsert = mysqli_prepare($conn, "INSERT INTO users (email, username, password, is_verified, photo_url) VALUES (?, ?, '', 0, ?)");
    mysqli_stmt_bind_param($stmtInsert, "sss", $email, $name, $photo);

    if (mysqli_stmt_execute($stmtInsert)) {
        // ✅ Kirim email notifikasi ke admin
        sendAdminNotificationEmail($email, $name);
    }

    echo json_encode([
        'status' => 'error',
        'message' => 'Akun Anda berhasil didaftarkan. Tunggu verifikasi admin.'
    ]);
}
