<?php
session_start();
require 'config/db.php';
require 'config/google_config.php';

if (isset($_GET['code'])) {
    $code = $_GET['code'];
    
    // 1. GET ACCESS TOKEN
    $url = 'https://oauth2.googleapis.com/token';
    $data = [
        'code' => $code,
        'client_id' => GOOGLE_CLIENT_ID,
        'client_secret' => GOOGLE_CLIENT_SECRET,
        'redirect_uri' => GOOGLE_REDIRECT_URL,
        'grant_type' => 'authorization_code'
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);
    
    if (!isset($response['access_token'])) { 
        die("Error: Google Login Failed. Please try again."); 
    }
    $token = $response['access_token'];

    // 2. GET USER PROFILE
    $url = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=$token";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $user_info = json_decode(curl_exec($ch), true);
    curl_close($ch);
    
    $g_email = $user_info['email'];
    $g_name = $user_info['name'];
    $g_id = $user_info['id'];

    // 3. CHECK OR CREATE USER
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$g_email]);
    $user = $stmt->fetch();

    if ($user) {
        // LOGIN EXISTING USER
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['role'] = $user['role'];
        $_SESSION['reseller_status'] = $user['reseller_status'] ?? 'none';
        
        // Optional: Update Google ID if missing
        if(empty($user['google_id'])) {
            $pdo->prepare("UPDATE users SET google_id=? WHERE id=?")->execute([$g_id, $user['id']]);
        }
    } else {
        // CREATE NEW USER
        $pass = password_hash(bin2hex(random_bytes(10)), PASSWORD_DEFAULT); // Random secure password
        $ref_code = strtoupper(substr(str_replace(' ', '', $g_name), 0, 4) . rand(100, 999));
        
        $stmt = $pdo->prepare("INSERT INTO users (name, email, password_hash, google_id, referral_code, role) VALUES (?, ?, ?, ?, ?, 'user')");
        $stmt->execute([$g_name, $g_email, $pass, $g_id, $ref_code]);
        
        $_SESSION['user_id'] = $pdo->lastInsertId();
        $_SESSION['user_name'] = $g_name;
        $_SESSION['role'] = 'user';
        $_SESSION['reseller_status'] = 'none';
    }

    // 4. REDIRECT
    if (isset($_SESSION['redirect_url'])) {
        $go_to = $_SESSION['redirect_url'];
        unset($_SESSION['redirect_url']);
        header("Location: " . $go_to);
    } else {
        header("Location: profile.php");
    }
    exit();
} else {
    // If accessed directly without code
    header("Location: login.php");
    exit();
}
?>