<?php
/**
 * fampay_oauth_start.php
 *
 * Verify button (for FamPay rows) now lands here instead of showing a
 * manual "enter UPI / Gmail / App Password" popup. This just redirects
 * the merchant to Google's real login/consent screen.
 */
// Some hosts default the session cookie to SameSite=Strict, which browsers
// then refuse to send back when Google redirects the user to
// fampay_oauth_callback.php (a cross-site navigation) - that silently loses
// the session and shows "Session Expire Ho Gaya" for some users. Lax still
// sends the cookie on this kind of top-level GET redirect, so set it
// explicitly here rather than relying on the server's default.
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'samesite' => 'Lax',
]);
session_start();
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/../includes/google_oauth.php';

if (!isset($_SESSION['username'])) {
    header('Location: index');
    exit;
}

$mobileClean = isset($_GET['mobile']) ? preg_replace('/[^0-9]/', '', $_GET['mobile']) : '';
if ($mobileClean === '') {
    header('Location: connect_merchant');
    exit;
}

$sessionMobileEsc = mysqli_real_escape_string($conn, $_SESSION['username']);
$userRes = mysqli_query($conn, "SELECT * FROM users WHERE mobile='$sessionMobileEsc'");
$user = $userRes ? mysqli_fetch_assoc($userRes) : null;

if (!$user) {
    header('Location: index');
    exit;
}

if (empty($site_settings['google_client_id']) || empty($site_settings['google_client_secret']) || empty($site_settings['google_redirect_uri'])) {
    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script><script>
        Swal.fire({
            icon: "error",
            title: "Google Login Setup Nahi Hai",
            text: "Admin ne Website Manage page par Google Client ID/Secret/Redirect URI abhi set nahi kiya hai.",
            confirmButtonText: "Ok"
        }).then(function(){ window.location.href = "connect_merchant"; });
    </script>';
    exit;
}

// Standard OAuth CSRF protection: random state stored server-side against
// this browser session, verified again in the callback.
$state = bin2hex(random_bytes(16));
$_SESSION['fampay_oauth_state']      = $state;
$_SESSION['fampay_oauth_mobile']     = $mobileClean;
$_SESSION['fampay_oauth_user_token'] = $user['user_token'];

$authorizeUrl = google_oauth_authorize_url($state, $site_settings);
header('Location: ' . $authorizeUrl);
exit;
