<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/oauth.php';

// Ensure users table exists
db()->query("CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255),
  email VARCHAR(255) UNIQUE NOT NULL,
  password_hash VARCHAR(255),
  google_id VARCHAR(255),
  avatar_url VARCHAR(255),
  reset_token VARCHAR(255),
  reset_expires_at DATETIME,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Basic state check
if (!isset($_GET['state']) || $_GET['state'] !== ($_SESSION['oauth_state'] ?? null)) {
  die('Invalid OAuth state.');
}
if (!isset($_GET['code'])) {
  die('Missing authorization code.');
}

// Exchange code for tokens
$postData = http_build_query([
  'code' => $_GET['code'],
  'client_id' => GOOGLE_CLIENT_ID,
  'client_secret' => GOOGLE_CLIENT_SECRET,
  'redirect_uri' => GOOGLE_REDIRECT_URI,
  'grant_type' => 'authorization_code',
]);
$tokenCtx = stream_context_create([
  'http' => [
    'method' => 'POST',
    'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
    'content' => $postData,
    'ignore_errors' => true,
  ],
]);
$tokenJson = file_get_contents('https://oauth2.googleapis.com/token', false, $tokenCtx);
$token = json_decode($tokenJson, true);
if (empty($token['access_token'])) {
  die('Failed to obtain access token.');
}

// Fetch profile
$profileCtx = stream_context_create([
  'http' => [
    'method' => 'GET',
    'header' => "Authorization: Bearer " . $token['access_token'] . "\r\n",
    'ignore_errors' => true,
  ],
]);
$profileJson = file_get_contents('https://openidconnect.googleapis.com/v1/userinfo', false, $profileCtx);
$profile = json_decode($profileJson, true);
if (empty($profile['email'])) {
  die('Failed to load user profile.');
}

// Upsert user by google_id or email
$googleId = $profile['sub'] ?? null;
$email = $profile['email'];
$name = ($profile['name'] ?? '');
$avatar = ($profile['picture'] ?? '');

$userId = null;

// Try by google_id
$stmt = db()->prepare("SELECT id FROM users WHERE google_id = ?");
$stmt->bind_param("s", $googleId);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if ($row) {
  $userId = (int)$row['id'];
} else {
  // Try by email
  $stmt = db()->prepare("SELECT id FROM users WHERE email = ?");
  $stmt->bind_param("s", $email);
  $stmt->execute();
  $res = $stmt->get_result();
  $row = $res->fetch_assoc();
  if ($row) {
    $userId = (int)$row['id'];
    // attach google_id and avatar/name
    $stmt = db()->prepare("UPDATE users SET google_id = ?, name = ?, avatar_url = ? WHERE id = ?");
    $stmt->bind_param("sssi", $googleId, $name, $avatar, $userId);
    $stmt->execute();
  } else {
    // create new user
    $stmt = db()->prepare("INSERT INTO users (name, email, google_id, avatar_url) VALUES (?,?,?,?)");
    $stmt->bind_param("ssss", $name, $email, $googleId, $avatar);
    $stmt->execute();
    $userId = (int)$stmt->insert_id;
  }
}

$_SESSION['user_id'] = $userId;
$_SESSION['user_name'] = $name ?: $email;

$next = $_SESSION['oauth_next'] ?? '/WATCHING/index.php';
unset($_SESSION['oauth_state'], $_SESSION['oauth_next']);
header('Location: ' . $next);
exit;