<?php
require_once '../includes/config.php'; 

if (isset($_GET['code'])) {
    try {
        // 1. Ambil token dari Google
        $token = $google_client->fetchAccessTokenWithAuthCode($_GET['code']);
        
        if (!isset($token['error'])) {
            $google_client->setAccessToken($token['access_token']);

            // 2. Ambil profil user
            $google_oauth = new Google_Service_Oauth2($google_client);
            $google_account_info = $google_oauth->userinfo->get();

            $email     = $google_account_info->email;
            $nama      = $google_account_info->name;
            $google_id = $google_account_info->id;
            $foto      = $google_account_info->picture;

            // 3. Cek apakah pelapor sudah ada di database (berdasarkan email)
            $stmt = $pdo->prepare("SELECT * FROM pelapor WHERE email = ?");
            $stmt->execute([$email]);
            $user = $stmt->fetch();

            if ($user) {
                // UPDATE google_id dan foto jika sebelumnya mereka daftar manual
                $update = $pdo->prepare("UPDATE pelapor SET google_id = ?, foto = ? WHERE email = ?");
                $update->execute([$google_id, $foto, $email]);
                
                $pelapor_id = $user['id'];
                $pelapor_nama = $user['nama_lengkap'];
            } else {
                // Jika user benar-benar baru, buat akun otomatis
                $insert = $pdo->prepare("INSERT INTO pelapor (google_id, nama_lengkap, email, foto) VALUES (?, ?, ?, ?)");
                $insert->execute([$google_id, $nama, $email, $foto]);
                
                $pelapor_id = $pdo->lastInsertId();
                $pelapor_nama = $nama;
            }

            // 4. Set Session (Sesuaikan dengan variabel di login_pelapor.php Anda)
            $_SESSION['pelapor_id'] = $pelapor_id;
            $_SESSION['pelapor_nama'] = $pelapor_nama;
            $_SESSION['pelapor_foto'] = $foto;

            session_regenerate_id(true);
            header("Location: index.php");
            exit();

        } else {
            die("Error Google Auth: " . $token['error']);
        }
    } catch (Exception $e) {
        die("Terjadi kesalahan sistem: " . $e->getMessage());
    }
} else {
    header("Location: login_pelapor.php");
    exit();
}