<?php
session_start();
require_once 'db.php';

// Konfigurasi Google OAuth (Wajib Diisi oleh User)
$google_client_id = '808762497378-hof7dlvqqpl7je56sh6joufao404u52p.apps.googleusercontent.com'; 
$google_client_secret = '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';
$google_redirect_uri = 'http://localhost/monitordaerah12/google_callback.php';

// Jika ada error dari Google (misal user batal login)
if (isset($_GET['error'])) {
    $_SESSION['login_error'] = "Login dibatalkan oleh pengguna.";
    header('Location: login.php');
    exit;
}

// Jika berhasil mendapatkan kode otorisasi
if (isset($_GET['code'])) {
    $code = $_GET['code'];

    // 1. Tukar kode dengan Access Token
    $token_url = 'https://oauth2.googleapis.com/token';
    $post_fields = [
        'code' => $code,
        'client_id' => $google_client_id,
        'client_secret' => $google_client_secret,
        'redirect_uri' => $google_redirect_uri,
        'grant_type' => 'authorization_code'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $token_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Jika di lokal mengalami masalah SSL, gunakan baris berikut. Namun di production wajib true.
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    
    $token_response = curl_exec($ch);
    curl_close($ch);
    
    $token_data = json_decode($token_response, true);
    
    if (isset($token_data['error'])) {
        die("Error saat mengambil access token: " . htmlspecialchars($token_data['error_description']));
    }

    $access_token = $token_data['access_token'];

    // 2. Ambil Profil Pengguna menggunakan Access Token
    $profile_url = 'https://www.googleapis.com/oauth2/v2/userinfo';
    $ch_profile = curl_init();
    curl_setopt($ch_profile, CURLOPT_URL, $profile_url);
    curl_setopt($ch_profile, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch_profile, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $access_token
    ]);
    curl_setopt($ch_profile, CURLOPT_SSL_VERIFYPEER, false);

    $profile_response = curl_exec($ch_profile);
    curl_close($ch_profile);
    
    $profile_data = json_decode($profile_response, true);

    if (isset($profile_data['error'])) {
        die("Error saat mengambil profil pengguna.");
    }

    $email = $profile_data['email'];
    $google_id = $profile_data['id'];

    // 3. Proses Login di Sistem
    // Memungkinkan satu akun user memiliki banyak email (dipisahkan oleh koma pada kolom email di database)
    $stmt = $pdo->prepare("SELECT * FROM users WHERE FIND_IN_SET(?, REPLACE(email, ' ', '')) > 0 LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        // Cek status instansi untuk admin instansi
        $can_login = true;
        if ($user['role'] !== 'superadmin' && !empty($user['instansi_id'])) {
            $stmt_instansi = $pdo->prepare("SELECT status FROM instansi WHERE id = ?");
            $stmt_instansi->execute([$user['instansi_id']]);
            $instansi = $stmt_instansi->fetch(PDO::FETCH_ASSOC);
            
            if ($instansi && $instansi['status'] !== 'aktif') {
                $can_login = false;
                $_SESSION['login_error'] = "Akses ditolak: Akun Instansi sedang ditangguhkan (Suspend). Silakan hubungi Superadmin.";
                header('Location: login.php');
                exit;
            }
        }

        if ($can_login) {
            // Update google_id jika sebelumnya kosong (untuk linking akun pertama kali)
            if (empty($user['google_id'])) {
                $stmt_update = $pdo->prepare("UPDATE users SET google_id = ? WHERE id = ?");
                $stmt_update->execute([$google_id, $user['id']]);
            }

            // Set session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['instansi_id'] = $user['instansi_id'];

            if($user['role'] === 'superadmin') {
                header("Location: superadmin.php");
            } else {
                header("Location: index.php");
            }
            exit;
        }
    } else {
        // Akun belum terdaftar (Ditolak)
        $_SESSION['login_error'] = "Akses ditolak: Email Google Anda ('$email') tidak memiliki otorisasi untuk masuk ke akun manapun. Silakan hubungi Superadmin untuk mendaftarkan email Anda.";
        header('Location: login.php');
        exit;
    }

} else {
    // Akses langsung tanpa kode
    header('Location: login.php');
    exit;
}
?>
