<?php
require_once __DIR__ . "/../includes/config.php";
require_once __DIR__ . "/../includes/functions.php";

/*
1) Google Cloud Console -> OAuth Client -> Web Application
2) Authorized redirect URI:
   https://YOURDOMAIN.co.uk/auth/google_callback.php
3) Put CLIENT_ID and CLIENT_SECRET here
*/

define('GOOGLE_CLIENT_ID', 'YOUR_CLIENT_ID');
define('GOOGLE_CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
define('GOOGLE_REDIRECT_URI', 'https://YOURDOMAIN.co.uk/auth/google_callback.php');

if (!isset($_GET['code'])) {
  $authUrl = "https://accounts.google.com/o/oauth2/v2/auth"
    . "?response_type=code"
    . "&client_id=" . urlencode(GOOGLE_CLIENT_ID)
    . "&redirect_uri=" . urlencode(GOOGLE_REDIRECT_URI)
    . "&scope=" . urlencode("openid email profile")
    . "&access_type=online"
    . "&prompt=select_account";
  header("Location: $authUrl");
  exit;
}

// Exchange code for token
$code = $_GET['code'];

$tokenResp = file_get_contents("https://oauth2.googleapis.com/token", false, stream_context_create([
  'http' => [
    'method'  => 'POST',
    'header'  => "Content-Type: application/x-www-form-urlencoded",
    'content' => http_build_query([
      'code' => $code,
      'client_id' => GOOGLE_CLIENT_ID,
      'client_secret' => GOOGLE_CLIENT_SECRET,
      'redirect_uri' => GOOGLE_REDIRECT_URI,
      'grant_type' => 'authorization_code'
    ])
  ]
]));

$data = json_decode($tokenResp, true);
if (empty($data['id_token'])) die("Google auth failed.");

$idToken = $data['id_token'];

// Validate token + get user info (simple decode via Google endpoint)
$info = json_decode(file_get_contents("https://oauth2.googleapis.com/tokeninfo?id_token=" . urlencode($idToken)), true);
$email = strtolower($info['email'] ?? '');
$name  = $info['name'] ?? 'Google User';
$gid   = $info['sub'] ?? '';

if (!$email || !$gid) die("Invalid Google user.");

// Find or create user
$stmt = $pdo->prepare("SELECT * FROM users WHERE email=? LIMIT 1");
$stmt->execute([$email]);
$user = $stmt->fetch();

if (!$user) {
  $pdo->prepare("INSERT INTO users (name,email,google_id) VALUES (?,?,?)")->execute([$name,$email,$gid]);
  $userId = (int)$pdo->lastInsertId();
} else {
  $userId = (int)$user['id'];
  if (empty($user['google_id'])) {
    $pdo->prepare("UPDATE users SET google_id=? WHERE id=?")->execute([$gid,$userId]);
  }
}

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

header("Location: /");
exit;
