<?php
/**
 * fampay_oauth_callback.php
 *
 * Google redirects the merchant's browser back here after they approve
 * (or cancel) access. This is the Google Cloud "Authorized redirect URI" -
 * it must be set to this file's full https URL, and that same URL must be
 * saved in Website Manage -> Google Redirect URI so both sides match.
 */
// Must match fampay_oauth_start.php's cookie params exactly, otherwise this
// is a different "session" as far as the browser is concerned and the
// state/mobile/user_token saved there won't be visible here.
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'samesite' => 'Lax',
]);
session_start();
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/../includes/google_oauth.php';

/**
 * Always renders a real HTML page (not just a bare <script> tag), so the
 * merchant sees *something* even if the SweetAlert CDN is slow/blocked.
 * $debug (only shown when present) helps diagnose failures during setup -
 * it's plain text, not sensitive tokens.
 */
function fampay_oauth_render($title, $message, $icon = 'error', $debug = null) {
    $color = $icon === 'success' ? '#43e97b' : '#ff6b6b';
    $delaySeconds = $debug ? 12 : 2;
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="refresh" content="<?php echo $delaySeconds; ?>;url=connect_merchant">
        <title><?php echo htmlspecialchars($title); ?></title>
        <style>
            body{margin:0;background:#0a0a12;color:#fff;font-family:-apple-system,Segoe UI,Roboto,sans-serif;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;box-sizing:border-box}
            .card{max-width:420px;text-align:center}
            .icon{font-size:48px;color:<?php echo $color; ?>;margin-bottom:16px}
            h2{margin:0 0 10px}
            p{color:rgba(255,255,255,.7);line-height:1.5;font-size:.95rem}
            .debug{margin-top:16px;background:rgba(255,255,255,.06);border-radius:8px;padding:10px 12px;font-size:.72rem;color:rgba(255,255,255,.55);text-align:left;word-break:break-word;white-space:pre-wrap}
            a.btn{display:inline-block;margin-top:20px;background:linear-gradient(135deg,#6c63ff,#e040fb);color:#fff;text-decoration:none;padding:10px 22px;border-radius:8px;font-weight:600;font-size:.9rem}
        </style>
    </head>
    <body>
        <div class="card">
            <div class="icon"><?php echo $icon === 'success' ? '&#10004;' : '&#10006;'; ?></div>
            <h2><?php echo htmlspecialchars($title); ?></h2>
            <p><?php echo htmlspecialchars($message); ?></p>
            <?php if ($debug): ?>
                <div class="debug"><?php echo htmlspecialchars($debug); ?></div>
            <?php endif; ?>
            <a class="btn" href="connect_merchant">Connect Merchant par wapas jaayein</a>
        </div>
        <script>
            setTimeout(function(){ window.location.href = "connect_merchant"; }, <?php echo $delaySeconds * 1000; ?>);
        </script>
    </body>
    </html>
    <?php
    exit;
}

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

if (isset($_GET['error'])) {
    fampay_oauth_render('Login Cancel Ho Gaya', 'Aapne Google login/permission cancel kar diya. Dobara Verify pe tap karke try karein.', 'error', 'error=' . $_GET['error']);
}

if (
    !isset($_GET['code'], $_GET['state']) ||
    !isset($_SESSION['fampay_oauth_state']) ||
    !hash_equals($_SESSION['fampay_oauth_state'], $_GET['state'])
) {
    fampay_oauth_render('Request Expire Ho Gayi', 'Yeh login request invalid ya expire ho gayi hai. Connect Merchant page pe jaakar dobara Verify pe tap karein.');
}

$mobile    = $_SESSION['fampay_oauth_mobile'] ?? '';
$userToken = $_SESSION['fampay_oauth_user_token'] ?? '';
unset($_SESSION['fampay_oauth_state'], $_SESSION['fampay_oauth_mobile'], $_SESSION['fampay_oauth_user_token']);

if ($mobile === '' || $userToken === '') {
    fampay_oauth_render('Session Expire Ho Gaya', 'Dobara Connect Merchant page se Verify pe tap karein.');
}

if (empty($site_settings['google_client_id']) || empty($site_settings['google_client_secret']) || empty($site_settings['google_redirect_uri'])) {
    fampay_oauth_render('Google Login Setup Adhoora Hai', 'Website Manage page par Google Client ID / Secret / Redirect URI teeno save karein, phir dobara try karein.');
}

if (!function_exists('curl_init')) {
    fampay_oauth_render('Server Configuration Error', 'PHP curl extension is server par enabled nahi hai. Hosting provider se PHP curl extension enable karwayein.');
}

$tokens = google_oauth_exchange_code($_GET['code'], $site_settings);
if (!$tokens || empty($tokens['access_token'])) {
    $debugMsg = is_array($tokens) ? json_encode($tokens) : 'Google token endpoint se koi response nahi mila (curl/network issue ho sakta hai).';
    fampay_oauth_render('Google Se Token Nahi Mila', 'Token exchange fail ho gaya. Neeche di gayi detail check karein - aksar yeh Redirect URI mismatch ya Client Secret galat hone se hota hai.', 'error', $debugMsg);
}

$userinfo = google_oauth_get_userinfo($tokens['access_token']);
$gmail = $userinfo['email'] ?? '';
if ($gmail === '') {
    fampay_oauth_render('Email Nahi Mil Paaya', 'Google account ka email address nahi mil paaya.', 'error', $userinfo ? json_encode($userinfo) : 'no userinfo response');
}

$refreshToken = $tokens['refresh_token'] ?? null;
$accessToken  = $tokens['access_token'];
$expiry       = time() + (int)($tokens['expires_in'] ?? 3300);

$mobileEsc      = mysqli_real_escape_string($conn, $mobile);
$userTokenEsc   = mysqli_real_escape_string($conn, $userToken);
$gmailEsc       = mysqli_real_escape_string($conn, $gmail);
$accessTokenEsc = mysqli_real_escape_string($conn, $accessToken);

$existingRes = mysqli_query($conn, "SELECT id, refresh_token FROM fampay_tokens WHERE user_token='$userTokenEsc' AND phoneNumber='$mobileEsc' LIMIT 1");
$existing = $existingRes ? mysqli_fetch_assoc($existingRes) : null;

// Google only sends refresh_token on the *first* consent for an app+account
// pair. If the merchant is reconnecting, keep the previously stored one.
if (!$refreshToken && $existing && !empty($existing['refresh_token'])) {
    $refreshToken = $existing['refresh_token'];
}
$refreshTokenEsc = $refreshToken ? mysqli_real_escape_string($conn, $refreshToken) : '';

if ($existing) {
    $updateOk = mysqli_query($conn, "UPDATE fampay_tokens SET gmail='$gmailEsc', refresh_token='$refreshTokenEsc', access_token='$accessTokenEsc', token_expiry=$expiry, status='Active' WHERE id=" . (int)$existing['id']);
} else {
    $userRowRes = mysqli_query($conn, "SELECT id FROM users WHERE user_token='$userTokenEsc' LIMIT 1");
    $userRow = $userRowRes ? mysqli_fetch_assoc($userRowRes) : null;
    $uid = $userRow ? (int)$userRow['id'] : 0;
    $updateOk = mysqli_query($conn, "INSERT INTO fampay_tokens (user_token, user_id, phoneNumber, upi_id, gmail, app_password, refresh_token, access_token, token_expiry, status) VALUES ('$userTokenEsc', $uid, '$mobileEsc', '', '$gmailEsc', '', '$refreshTokenEsc', '$accessTokenEsc', $expiry, 'Active')");
}

if (!$updateOk) {
    fampay_oauth_render('Database Error', 'Token mila lekin save karte waqt database error aaya. Confirm karein ki sql/fampay_oauth_upgrade.sql run ho chuki hai.', 'error', mysqli_error($conn));
}

mysqli_query($conn, "UPDATE users SET fampay_connected='Yes' WHERE user_token='$userTokenEsc'");

fampay_oauth_render('Connected!', 'Aapka FamPay Gmail (' . $gmail . ') safaltapoorvak connect ho gaya.', 'success');
