<?php
/**
 * StudyTrack — Facebook OAuth 2.0 Callback Handler
 * URL: /fb-auth.php
 *
 * Flow:
 *   1. User clicks "Sign in with Facebook" → redirected to Facebook
 *   2. Facebook redirects back here         → exchange code for token
 *   3. Fetch user's Facebook profile        → create/login user in DB
 *   4. Redirect to dashboard                → done ✅
 */
require_once 'includes/config.php';

// ── Already logged in? ───────────────────────────────────────────
if (isLoggedIn()) {
    header('Location: ' . SITE_URL . '/dashboard.php');
    exit;
}

// ─────────────────────────────────────────────────────────────────
// STEP 1 — Build Facebook authorization URL
// ─────────────────────────────────────────────────────────────────
if (!isset($_GET['code']) && !isset($_GET['error'])) {
    $state = bin2hex(random_bytes(16));
    $_SESSION['fb_oauth_state'] = $state;

    $params = http_build_query([
        'client_id'     => FB_APP_ID,
        'redirect_uri'  => FB_REDIRECT_URI,
        'state'         => $state,
        'scope'         => 'email,public_profile',
        'response_type' => 'code',
    ]);

    header('Location: https://www.facebook.com/v19.0/dialog/oauth?' . $params);
    exit;
}

// ─────────────────────────────────────────────────────────────────
// STEP 2 — Handle errors from Facebook
// ─────────────────────────────────────────────────────────────────
if (isset($_GET['error'])) {
    $err = $_GET['error_reason'] ?? $_GET['error'] ?? 'unknown';
    header('Location: ' . SITE_URL . '/login.php?fb_error=' . urlencode($err));
    exit;
}

// ─────────────────────────────────────────────────────────────────
// STEP 3 — Validate CSRF state
// ─────────────────────────────────────────────────────────────────
if (empty($_GET['state']) || $_GET['state'] !== ($_SESSION['fb_oauth_state'] ?? '')) {
    header('Location: ' . SITE_URL . '/login.php?fb_error=state_mismatch');
    exit;
}
unset($_SESSION['fb_oauth_state']);

// ─────────────────────────────────────────────────────────────────
// STEP 4 — Exchange code for access token
// ─────────────────────────────────────────────────────────────────
$tokenUrl = 'https://graph.facebook.com/v19.0/oauth/access_token?' . http_build_query([
    'client_id'     => FB_APP_ID,
    'client_secret' => FB_APP_SECRET,
    'redirect_uri'  => FB_REDIRECT_URI,
    'code'          => $_GET['code'],
]);

$tokenData = fbHttpGet($tokenUrl);

if (!$tokenData || empty($tokenData['access_token'])) {
    header('Location: ' . SITE_URL . '/login.php?fb_error=token_failed');
    exit;
}

$accessToken = $tokenData['access_token'];

// ─────────────────────────────────────────────────────────────────
// STEP 5 — Fetch Facebook user profile
// ─────────────────────────────────────────────────────────────────
$profileUrl = 'https://graph.facebook.com/v19.0/me?' . http_build_query([
    'fields'       => 'id,name,email,picture.type(large)',
    'access_token' => $accessToken,
]);

$profile = fbHttpGet($profileUrl);

if (!$profile || empty($profile['id'])) {
    header('Location: ' . SITE_URL . '/login.php?fb_error=profile_failed');
    exit;
}

$facebookId  = $profile['id'];
$name        = $profile['name'] ?? 'Facebook User';
$email       = strtolower(trim($profile['email'] ?? ''));
$fbAvatar    = $profile['picture']['data']['url'] ?? null;

// Facebook sometimes doesn't provide email (user's privacy settings)
// In that case, we ask the user to enter their email on the terms page
$needsEmail = false;
if (!$email) {
    $email      = 'fb_' . $facebookId . '@facebook.placeholder'; // temp, replaced on terms page
    $needsEmail = true;
}

// ─────────────────────────────────────────────────────────────────
// STEP 6 — Find or create user in database
// ─────────────────────────────────────────────────────────────────
try {
    // Case A: User already linked with this Facebook ID
    $stmt = $pdo->prepare("SELECT * FROM users WHERE facebook_id = ?");
    $stmt->execute([$facebookId]);
    $user = $stmt->fetch();

    if (!$user) {
        // Case B: User exists with same email — link Facebook to it
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user) {
            if (!empty($user['is_disabled'])) {
                header('Location: ' . SITE_URL . '/login.php?suspended=1');
                exit;
            }
            // Link Facebook to existing account
            $pdo->prepare(
                "UPDATE users SET facebook_id=?, google_avatar=COALESCE(google_avatar,?), auth_provider='facebook', is_verified=1 WHERE id=?"
            )->execute([$facebookId, $fbAvatar, $user['id']]);

            $stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
            $stmt->execute([$user['id']]);
            $user = $stmt->fetch();

        } else {
            // Case C: Brand new user — store in session, redirect to terms page
            $_SESSION['fb_pending'] = [
                'name'        => $name,
                'email'       => $email,
                'facebook_id' => $facebookId,
                'fb_avatar'   => $fbAvatar,
                'needs_email' => $needsEmail,
            ];
            header('Location: ' . SITE_URL . '/fb-terms.php');
            exit;
        }
    }

    // Final check — account disabled?
    if (!empty($user['is_disabled'])) {
        header('Location: ' . SITE_URL . '/login.php?suspended=1');
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    // STEP 7 — Log user in
    // ─────────────────────────────────────────────────────────────
    session_regenerate_id(true);
    $_SESSION['user_id']    = $user['id'];
    $_SESSION['user_name']  = $user['name'];
    $_SESSION['user_email'] = $user['email'];
    $_SESSION['login_time'] = time();
    createDbSession($user['id']);

    header('Location: ' . SITE_URL . '/dashboard.php');
    exit;

} catch (PDOException $e) {
    error_log('Facebook auth DB error: ' . $e->getMessage());
    header('Location: ' . SITE_URL . '/login.php?fb_error=db_error');
    exit;
}

// ─────────────────────────────────────────────────────────────────
// Helper: GET request using cURL
// ─────────────────────────────────────────────────────────────────
function fbHttpGet(string $url): ?array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_USERAGENT      => 'StudyTrack/1.0',
    ]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) { error_log('Facebook OAuth cURL error: ' . $err); return null; }
    return json_decode($res, true);
}