<?php
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';
require_once __DIR__ . '/../core/session.php';

// Detectamos si es una redirección normal (GET) o el antiguo fetch (POST)
$is_ajax = false;
$code = $_GET['code'] ?? null;

if (!$code) {
    $input = json_decode(file_get_contents('php://input'), true);
    $code = $input['code'] ?? null;
    $is_ajax = true;
}

if (!$code) {
    if (isset($_GET['error'])) {
        header('Location: /login.php?error=Acceso denegado por el usuario.');
        exit;
    }
    die('Código no recibido.');
}

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$redirect_uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . '/auth/google_callback.php';

$post_redirect_uri = $is_ajax ? 'postmessage' : $redirect_uri;

// Intercambiar código por tokens
$ch = curl_init('https://oauth2.googleapis.com/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'client_id' => GOOGLE_CLIENT_ID,
    'client_secret' => GOOGLE_CLIENT_SECRET, 
    'code' => $code,
    'grant_type' => 'authorization_code',
    'redirect_uri' => $post_redirect_uri
]));

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$response = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

if ($response === false) {
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => 'Error de conexión cURL: ' . $curl_error]);
    } else {
        header('Location: /login.php?error=' . urlencode('Error de conexión cURL: ' . $curl_error));
    }
    exit;
}

$tokenData = json_decode($response, true);

if (!isset($tokenData['access_token'])) {
    $errorMsg = $tokenData['error_description'] ?? $tokenData['error'] ?? $response;
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => 'Error de Google: ' . $errorMsg]);
    } else {
        header('Location: /login.php?error=' . urlencode('Sesión expirada o código inválido. Por favor, intenta de nuevo.'));
    }
    exit;
}

// Decodificar el id_token para saber quién es
$payload_parts = explode('.', $tokenData['id_token']);
$payload = json_decode(base64_decode($payload_parts[1]), true);

// Validaciones de seguridad de ICYLAB
if (($payload['hd'] ?? '') !== GOOGLE_ALLOWED_DOMAIN) {
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => 'Acceso restringido a cuentas corporativas.']);
    } else {
        header('Location: /login.php?error=' . urlencode('Acceso restringido a cuentas corporativas.'));
    }
    exit;
}

$email = $payload['email'];
$google_id = $payload['sub'];
$name = $payload['name'] ?? '';

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

// Si el usuario no existe, lo creamos inactivo
if (!$user) {
    $stmt = $pdo->prepare("
        INSERT INTO users
        (google_id, name, email, role, area, is_active, status, last_login)
        VALUES (?, ?, ?, NULL, NULL, 0, 'inactive', NOW())
    ");
    $stmt->execute([$google_id, $name, $email]);
    $user_id = $pdo->lastInsertId();

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

if ((int)$user['is_active'] !== 1 || $user['status'] !== 'active') {
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => 'Cuenta no autorizada.']);
    } else {
        header('Location: /login.php?error=' . urlencode('Cuenta no autorizada. Contacte a administración.'));
    }
    exit;
}

// Calcular expiración
$expires_in = $tokenData['expires_in'] ?? 3599;
$expires_at = date('Y-m-d H:i:s', time() + $expires_in);

// Guardamos el refresh_token si Google lo entrega
$refreshTokenSql = isset($tokenData['refresh_token']) ? ", google_refresh_token = '" . $tokenData['refresh_token'] . "'" : "";

$stmt = $pdo->prepare("
    UPDATE users 
    SET google_id = ?, 
        name = ?,
        google_access_token = ?, 
        google_token_expires = ?, 
        last_login = NOW()
        $refreshTokenSql
    WHERE id = ?
");

$stmt->execute([
    $google_id,
    $name,
    $tokenData['access_token'],
    $expires_at,
    $user['id']
]);

$_SESSION['user'] = array(
    'id' => $user['id'],
    'name' => $user['name'],
    'email' => $user['email'],
    'role' => $user['role'],
    'status' => $user['status']
);

if ($is_ajax) {
    echo json_encode(['success' => true]);
} else {
    header('Location: /modules/dashboard/');
}
exit;