<?php
session_start();
require 'db_connect.php'; // Defines $users_db

// 1. YOUR GOOGLE API CREDENTIALS
$clientID = '22619473984-hqekvoshb4dmmr7bm647ngmbqj59pibd.apps.googleusercontent.com';
$clientSecret = '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';
$redirectUri = 'https://www.astrosubhajitfpa.in/google_oauth.php'; 

// 2. CATCHING THE RESPONSE FROM GOOGLE
if (isset($_GET['code'])) {
    $token_url = 'https://oauth2.googleapis.com/token';
    $data = [
        'code' => $_GET['code'],
        'client_id' => $clientID,
        'client_secret' => $clientSecret,
        'redirect_uri' => $redirectUri,
        'grant_type' => 'authorization_code'
    ];

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

    $token_data = json_decode($response, true);

    if (isset($token_data['access_token'])) {
        $profile_url = 'https://www.googleapis.com/oauth2/v2/userinfo?access_token=' . $token_data['access_token'];
        $ch = curl_init($profile_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $profile_response = curl_exec($ch);
        curl_close($ch);

        $user_info = json_decode($profile_response, true);
        $email = $user_info['email'];
        $name = $user_info['name'];

        // --- REAL DATABASE LOGIC ---
        // Check if user already exists
        $stmt = $users_db->prepare("SELECT id, name, phone FROM clients WHERE email = ?");
        $stmt->execute([$email]);
        $client = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($client) {
            // Existing User: Log them in
            $_SESSION['client_id'] = $client['id'];
            $_SESSION['client_name'] = $client['name'];
            
            // If they haven't finished profile (no phone), send them to complete_profile.php
            if (empty($client['phone'])) {
                header("Location: complete_profile.php");
            } else {
                header("Location: dashboard.php");
            }
        } else {
            // New User: Create account
            $stmt = $users_db->prepare("INSERT INTO clients (auth_provider, name, email) VALUES ('google', ?, ?)");
            $stmt->execute([$name, $email]);
            
            $_SESSION['client_id'] = $users_db->lastInsertId();
            $_SESSION['client_name'] = $name;
            
            // Force them to complete profile (add phone/pic)
            header("Location: complete_profile.php");
        }
        exit();
    } else {
        die("Authentication Error: Google did not return an access token.");
    }
}

// 3. SENDING THE USER TO GOOGLE
$auth_url = 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query([
    'client_id' => $clientID,
    'redirect_uri' => $redirectUri,
    'response_type' => 'code',
    'scope' => 'email profile'
]);

header("Location: $auth_url");
exit();
?>