<?php
/**
 * auth/google_callback.php — Step 2 of Google sign-in.
 * Verifies the state, exchanges the code for tokens, reads the Google
 * profile, finds-or-creates the customer, starts the session, and sends
 * the user into the app.
 */
session_start();
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/oauth.php';
require_once __DIR__ . '/_helpers.php';

/** Abort back to the sign-in screen with a friendly message. */
function dabil_oauth_fail(string $msg): void
{
    $_SESSION['login_error'] = $msg;
    header('Location: ../signin.php');
    exit;
}

// User declined, or Google returned an error.
if (($_GET['error'] ?? '') !== '') {
    dabil_oauth_fail('Google sign-in was cancelled.');
}

$code  = $_GET['code']  ?? '';
$state = $_GET['state'] ?? '';

if ($code === '') {
    dabil_oauth_fail('Google sign-in failed. Please try again.');
}
if (empty($_SESSION['oauth_state']) || !hash_equals($_SESSION['oauth_state'], $state)) {
    dabil_oauth_fail('Security check failed. Please try signing in again.');
}
unset($_SESSION['oauth_state']);

// 1. Exchange the authorization code for tokens.
$token = dabil_http_post('https://oauth2.googleapis.com/token', [
    'code'          => $code,
    'client_id'     => GOOGLE_CLIENT_ID,
    'client_secret' => GOOGLE_CLIENT_SECRET,
    'redirect_uri'  => dabil_google_redirect_uri(),
    'grant_type'    => 'authorization_code',
]);
if (empty($token['access_token'])) {
    dabil_oauth_fail('Could not verify your Google account. Please try again.');
}

// 2. Fetch the verified profile.
$info  = dabil_http_get('https://openidconnect.googleapis.com/v1/userinfo', $token['access_token']);
$email = strtolower(trim($info['email'] ?? ''));
if ($email === '' || empty($info['email_verified'])) {
    dabil_oauth_fail('Your Google email could not be verified.');
}

$providerUid = (string) ($info['sub'] ?? '');
$name        = trim($info['name'] ?? ($info['given_name'] ?? 'Dabil User'));
$avatar      = $info['picture'] ?? null;

// 3. Find or create the customer.
$user = dabil_find_or_create_customer($conn, $email, $name, $providerUid, $avatar, 'google');
if ($user === null) {
    dabil_oauth_fail('We could not create your account. Please try again.');
}
if ((int) $user['status'] !== 1) {
    dabil_oauth_fail('Your account is inactive. Please contact support.');
}

// 4. Start the session and go.
$redirect = dabil_safe_redirect($_SESSION['login_redirect'] ?? 'dashboard.php');
unset($_SESSION['login_redirect']);
dabil_start_customer_session($user);

header('Location: ../' . $redirect);
exit;
