<?php
require_once '../config/db.php';
require_once '../config/auth.php';

if (session_status() === PHP_SESSION_NONE) session_start();

// Get Google credentials from settings
function getSetting($conn, $key) {
    $key = $conn->real_escape_string($key);
    $r = $conn->query("SELECT setting_value FROM settings WHERE setting_key='$key'");
    return ($r && $r->num_rows > 0) ? $r->fetch_assoc()['setting_value'] : '';
}

$client_id     = getSetting($conn, 'google_client_id');
$client_secret = getSetting($conn, 'google_client_secret');
$redirect_uri  = 'http://' . $_SERVER['HTTP_HOST'] . '/lostfound_relink/auth/google_callback.php';

// Validate state to prevent CSRF
if (!isset($_GET['state']) || $_GET['state'] !== ($_SESSION['oauth_state'] ?? '')) {
    die('<div style="font-family:sans-serif;padding:40px;color:red">Invalid OAuth state. <a href="/lostfound_relink/auth/login.php">Go back</a></div>');
}
unset($_SESSION['oauth_state']);

if (isset($_GET['error'])) {
    header('Location: /lostfound_relink/auth/login.php?error=google_denied');
    exit;
}

if (!isset($_GET['code'])) {
    header('Location: /lostfound_relink/auth/login.php');
    exit;
}

// Exchange code for access token
$token_data = http_build_query([
    'code'          => $_GET['code'],
    'client_id'     => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri'  => $redirect_uri,
    'grant_type'    => 'authorization_code',
]);

$ch = curl_init('https://oauth2.googleapis.com/token');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $token_data,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
]);
$token_response = json_decode(curl_exec($ch), true);
curl_close($ch);

if (empty($token_response['access_token'])) {
    header('Location: /lostfound_relink/auth/login.php?error=token_failed');
    exit;
}

// Fetch Google user info
$ch = curl_init('https://www.googleapis.com/oauth2/v2/userinfo');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $token_response['access_token']],
]);
$google_user = json_decode(curl_exec($ch), true);
curl_close($ch);

if (empty($google_user['email'])) {
    header('Location: /lostfound_relink/auth/login.php?error=userinfo_failed');
    exit;
}

$google_id = $conn->real_escape_string($google_user['id']);
$email     = $conn->real_escape_string($google_user['email']);
$name      = $conn->real_escape_string($google_user['name'] ?? $google_user['email']);
$avatar    = $conn->real_escape_string($google_user['picture'] ?? '');

// Check if user already exists by google_id or email
$existing = $conn->query("SELECT * FROM users WHERE google_id='$google_id' OR email='$email'")->fetch_assoc();

if ($existing) {
    // Update google_id and avatar if missing
    if (empty($existing['google_id'])) {
        $conn->query("UPDATE users SET google_id='$google_id', avatar='$avatar' WHERE id={$existing['id']}");
    }

    // Check account status (admins always pass)
    if ($existing['role'] === 'admin') {
        // allow
    } elseif (($existing['account_status'] ?? 'pending') === 'pending') {
        header('Location: /lostfound_relink/auth/login.php?error=pending');
        exit;
    } elseif (($existing['account_status'] ?? 'pending') === 'rejected') {
        header('Location: /lostfound_relink/auth/login.php?error=rejected');
        exit;
    }

    $_SESSION['user_id'] = $existing['id'];
    $_SESSION['name']    = $existing['name'];
    $_SESSION['role']    = $existing['role'];
    $_SESSION['gender']  = $existing['gender'];
    header('Location: ' . ($existing['role'] === 'admin' ? '/lostfound_relink/admin/dashboard.php' : '/lostfound_relink/user/dashboard.php'));
    exit;
} else {
    // New user — register with pending status, redirect to complete profile
    $conn->query("INSERT INTO users (name, email, google_id, avatar, account_status) VALUES ('$name','$email','$google_id','$avatar','pending')");
    $new_id = $conn->insert_id;

    // Store in session for profile completion
    $_SESSION['google_pending_id'] = $new_id;
    $_SESSION['google_name']       = $google_user['name'] ?? '';
    $_SESSION['google_email']      = $google_user['email'];
    $_SESSION['google_avatar']     = $google_user['picture'] ?? '';

    header('Location: /lostfound_relink/auth/google_complete.php');
    exit;
}
