<?php
// auth/google-callback.php — Google OAuth 2.0 Callback Handler
// Handles both login and signup via Google
session_start();
require_once __DIR__ . '/../config.php';

// Validate state token (CSRF protection)
if (empty($_GET['state']) || empty($_SESSION['google_oauth_state']) || $_GET['state'] !== $_SESSION['google_oauth_state']) {
    header("Location: ../login.php?error=invalid_state");
    exit;
}
unset($_SESSION['google_oauth_state']);

// Google returned an error
if (!empty($_GET['error'])) {
    header("Location: ../login.php?error=google_denied");
    exit;
}

$code = $_GET['code'] ?? '';
if (empty($code)) {
    header("Location: ../login.php?error=no_code");
    exit;
}

// Exchange authorization code for access token
$token_url = 'https://oauth2.googleapis.com/token';
$token_data = [
    'code' => $code,
    'client_id' => GOOGLE_CLIENT_ID,
    'client_secret' => GOOGLE_CLIENT_SECRET,
    'redirect_uri' => GOOGLE_REDIRECT_URI,
    'grant_type' => 'authorization_code'
];

$ch = curl_init($token_url);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query($token_data),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
    CURLOPT_TIMEOUT => 15
]);
$token_response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code !== 200 || !$token_response) {
    header("Location: ../login.php?error=token_exchange_failed");
    exit;
}

$token_json = json_decode($token_response, true);
$access_token = $token_json['access_token'] ?? '';
if (empty($access_token)) {
    header("Location: ../login.php?error=no_access_token");
    exit;
}

// Fetch user info from Google
$userinfo_url = 'https://www.googleapis.com/oauth2/v2/userinfo';
$ch = curl_init($userinfo_url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Authorization: Bearer $access_token"],
    CURLOPT_TIMEOUT => 10
]);
$userinfo_response = curl_exec($ch);
curl_close($ch);

$google_user = json_decode($userinfo_response, true);
$google_id = $google_user['id'] ?? '';
$google_email = $google_user['email'] ?? '';
$google_name = $google_user['name'] ?? '';

if (empty($google_id) || empty($google_email)) {
    header("Location: ../login.php?error=incomplete_profile");
    exit;
}

// ------------------------------------------------------------------
// Look up user: first by google_id, then by email
// ------------------------------------------------------------------
$user = null;
$is_new_user = false;

// Try by google_id
$stmt = $conn->prepare("SELECT * FROM users WHERE google_id = ?");
$stmt->bind_param("s", $google_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Try by email
if (!$user) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->bind_param("s", $google_email);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    // Link Google ID to existing account
    if ($user && empty($user['google_id'])) {
        $stmt = $conn->prepare("UPDATE users SET google_id = ? WHERE id = ?");
        $stmt->bind_param("si", $google_id, $user['id']);
        $stmt->execute();
        $stmt->close();
    }
}

// ------------------------------------------------------------------
// No account found — create new user
// ------------------------------------------------------------------
if (!$user) {
    $is_new_user = true;
    $random_password = password_hash(bin2hex(random_bytes(16)), PASSWORD_DEFAULT);
    $role = 'member';

    $stmt = $conn->prepare("INSERT INTO users (org_name, email, password, role, google_id, is_verified) VALUES (?, ?, ?, ?, ?, 1)");
    if (!$stmt) {
        header("Location: ../login.php?error=create_failed&detail=" . urlencode($conn->error));
        exit;
    }
    $stmt->bind_param("sssss", $google_name, $google_email, $random_password, $role, $google_id);

    if (!$stmt->execute()) {
        header("Location: ../login.php?error=create_failed&detail=" . urlencode($stmt->error));
        exit;
    }
    $new_user_id = $conn->insert_id;
    $stmt->close();

    // Mark profile as incomplete (silently skip if column doesn't exist yet)
    $conn->query("UPDATE users SET profile_completed = 0 WHERE id = $new_user_id");

    // Auto-assign free Community package (same logic as signup.php)
    $pkg_res = $conn->query("SELECT id, token_amount, duration_days FROM subscription_packages WHERE price = 0 AND is_active = 1 LIMIT 1");
    if ($pkg_res && $pkg = $pkg_res->fetch_assoc()) {
        $end_date = date('Y-m-d H:i:s', strtotime("+" . ($pkg['duration_days'] ?? 3650) . " days"));
        $check_table = $conn->query("SHOW TABLES LIKE 'user_subscriptions'");
        if ($check_table && $check_table->num_rows > 0) {
            $stmt_sub = $conn->prepare("INSERT INTO user_subscriptions (user_id, package_id, tokens_remaining, start_date, end_date, status) VALUES (?, ?, ?, NOW(), ?, 'active')");
            if ($stmt_sub) {
                $stmt_sub->bind_param("iiis", $new_user_id, $pkg['id'], $pkg['token_amount'], $end_date);
                $stmt_sub->execute();
                $stmt_sub->close();
            }
        }
    }

    $user = [
        'id' => $new_user_id,
        'org_name' => $google_name,
        'email' => $google_email,
        'role' => 'user',
        'profile_completed' => 0
    ];

    // Audit log
    if (file_exists(__DIR__ . '/../util/audit_logger.php')) {
        include_once __DIR__ . '/../util/audit_logger.php';
        audit_log(
            $conn,
            'google_signup',
            'users',
            $new_user_id,
            $new_user_id,
            0,
            null,
            json_encode(['google_id' => $google_id, 'email' => $google_email]),
            "New account created via Google OAuth"
        );
    }
}

// ------------------------------------------------------------------
// Set session and redirect (mirrors login.php logic)
// ------------------------------------------------------------------
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['org_name'];
$_SESSION['user_email'] = $user['email'];
$_SESSION['user_role'] = $user['role'] ?? 'user';

if ($user['role'] === 'admin') {
    $_SESSION['admin_logged_in'] = true;
}

// ------------------------------------------------------------------
// Profile completion check — redirect new / incomplete users
// ------------------------------------------------------------------
$profile_done = intval($user['profile_completed'] ?? 0);
if (!$profile_done) {
    // Preserve the original redirect so complete-profile can use it after
    header("Location: ../complete-profile.php");
    exit;
}

// ------------------------------------------------------------------
// Redirect back to originating page or dashboard
// ------------------------------------------------------------------
$redirect_to = '../user_dashboard.php';
if (!empty($_SESSION['login_redirect'])) {
    $redirect_to = $_SESSION['login_redirect'];
    unset($_SESSION['login_redirect']);
}
header("Location: $redirect_to");
exit;
