<?php
session_start();
require_once __DIR__ . '/includes/functions.php';

if (!defined('GOOGLE_CLIENT_ID') || !defined('GOOGLE_CLIENT_SECRET')) {
    die("Google OAuth is not configured.");
}

if (isset($_GET['error'])) {
    header('Location: login.php?error=' . urlencode('Google login cancelled or failed.'));
    exit;
}

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

if (isset($_SESSION['oauth_state']) && isset($_GET['state']) && $_SESSION['oauth_state'] !== $_GET['state']) {
    header('Location: login.php?error=' . urlencode('Security check failed. Invalid state token.'));
    exit;
}

$code = $_GET['code'];

// Exchange code for token
$token_url = 'https://oauth2.googleapis.com/token';
$post_params = [
    'code' => $code,
    'client_id' => GOOGLE_CLIENT_ID,
    'client_secret' => GOOGLE_CLIENT_SECRET,
    'redirect_uri' => 'https://famgateway.in/auth-google-callback.php',
    'grant_type' => 'authorization_code'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$token_data = json_decode($response, true);

if (!isset($token_data['access_token'])) {
    header('Location: login.php?error=' . urlencode('Failed to get access token from Google.'));
    exit;
}

// Get user info
$userinfo_url = 'https://www.googleapis.com/oauth2/v2/userinfo';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $userinfo_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $token_data['access_token']]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$google_user = json_decode($response, true);

if (!isset($google_user['email'])) {
    header('Location: login.php?error=' . urlencode('Could not retrieve email from Google.'));
    exit;
}

$email = $google_user['email'];
$name = $google_user['name'] ?? 'User';
$picture = $google_user['picture'] ?? '';

if (isset($_SESSION['user_id'])) {
    $loggedInUser = getUserById($_SESSION['user_id']);
    if ($loggedInUser && strtolower($loggedInUser['email']) === strtolower($email)) {
        $loggedInUser['google_linked'] = 1;
        saveUser($loggedInUser);
        header('Location: profile.php?msg=linked');
        exit;
    } else {
        header('Location: profile.php?error=' . urlencode('Please select the Google account matching your registered email.'));
        exit;
    }
}

// Check if user exists
$user = getUserByEmail($email);

if ($user) {
    if (empty($user['google_linked'])) {
        header('Location: login.php?error=' . urlencode('Google sign-in is not enabled. Please login with email and enable it in Profile Settings.'));
        exit;
    }

    // Login existing user
    startSecureSession($user['id']);
    
    // Remember me cookie for 7 days
    $tokenPayload = json_encode(['id' => $user['id'], 'time' => time()]);
    setcookie('remember_token', encryptData($tokenPayload), time() + (7 * 24 * 60 * 60), '/');
    
    header('Location: dashboard.php');
    exit;
} else {
    // Auto-Register new user
    $sysSettings = getAdminSettings();
    if (empty($sysSettings['allow_registration'])) {
        header('Location: login.php?error=' . urlencode('New registrations are currently disabled by the site administrator.'));
        exit;
    }

    $userId = generateUserId();
    $apiKey = generateApiKey();
    $nowObj = nowIST();
    
    // Generate a random secure password for Google users
    $random_password = bin2hex(random_bytes(16));
    
    $newUser = [
        'id' => $userId,
        'name' => $name,
        'email' => $email,
        'phone' => '', 
        'password_hash' => password_hash($random_password, PASSWORD_DEFAULT),
        'created_at' => $nowObj->format('Y-m-d H:i:s'),
        'fampay_gmail' => '',
        'fampay_app_password_encrypted' => '',
        'fampay_upi_id' => '',
        'gmail_connected' => false,
        'google_linked' => 1,
        'api_keys' => [['key' => $apiKey, 'label' => 'Default', 'created_at' => $nowObj->format('Y-m-d H:i:s')]],
        'reset_chances' => 100,
        'avatar' => $picture, 
        'plan_id' => 'free',
        'plan_label' => 'Free',
        'plan_expires_at' => null,
        'total_requests' => 0,
        'total_success' => 0,
        'total_failed' => 0,
        'total_amount_received' => 0,
        'status' => 'active'
    ];

    saveUser($newUser);
    
    // Send Welcome Email
    $welcomeTpl = getEmailTemplate('welcome_email');
    if ($welcomeTpl) {
        $loginUrl = "https://famgateway.in/login.php";
        $body = str_replace(
            ['{name}', '{email}', '{login_url}'],
            [htmlspecialchars($name), htmlspecialchars($email), '<a href="'.$loginUrl.'">'.$loginUrl.'</a>'],
            $welcomeTpl['body']
        );
        $subject = str_replace(
            ['{name}', '{email}'],
            [$name, $email],
            $welcomeTpl['subject']
        );
        sendSMTPMail($email, $subject, $body, true);
    }
    
    // Log them in
    startSecureSession($userId);
    
    // Remember me cookie for 7 days
    $tokenPayload = json_encode(['id' => $userId, 'time' => time()]);
    setcookie('remember_token', encryptData($tokenPayload), time() + (7 * 24 * 60 * 60), '/');
    
    header('Location: dashboard.php');
    exit;
}
