<?php
require_once __DIR__ . '/includes/functions.php';

$error = '';

if (!isset($_GET['state']) || !isset($_SESSION['google_state']) || $_GET['state'] !== $_SESSION['google_state']) {
    $error = 'คำขอไม่ถูกต้อง (invalid state)';
}

unset($_SESSION['google_state']);

if (empty($error) && isset($_GET['code'])) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://oauth2.googleapis.com/token',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => 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',
        ]),
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code !== 200) {
        $error = 'ไม่สามารถยืนยันตัวตนกับ Google ได้';
    } else {
        $token_data = json_decode($response, true);
        if (!isset($token_data['id_token'])) {
            $error = 'ไม่ได้รับข้อมูลจาก Google';
        } else {
            $parts = explode('.', $token_data['id_token']);
            $encoded = strtr($parts[1], '-_', '+/');
            $encoded = str_pad($encoded, strlen($encoded) % 4 ? 4 - strlen($encoded) % 4 + strlen($encoded) : strlen($encoded), '=', STR_PAD_RIGHT);
            $payload = json_decode(base64_decode($encoded), true);

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

            if (empty($email)) {
                $error = 'ไม่ได้รับอีเมลจาก Google';
            } else {
                $db = getDB();

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

                if ($user) {
                    if (empty($user['google_id'])) {
                        $stmt = $db->prepare("UPDATE users SET google_id = ? WHERE id = ?");
                        $stmt->execute([$google_id, $user['id']]);
                    }
                    $_SESSION['logged_in'] = true;
                    $_SESSION['username'] = $user['name'];
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['staff_code'] = $user['staff_code'];
                    $_SESSION['role'] = $user['role'] ?? 'advisor';
                    $_SESSION['curriculum_id'] = $user['curriculum_id'];
                    header('Location: ' . BASE_URL . '/index.php');
                    exit;
                }

                $stmt = $db->prepare("SELECT * FROM students WHERE email = ?");
                $stmt->execute([$email]);
                $student = $stmt->fetch();

                if ($student) {
                    if (empty($student['google_id'])) {
                        try {
                            $stmt = $db->prepare("UPDATE students SET google_id = ? WHERE id = ?");
                            $stmt->execute([$google_id, $student['id']]);
                        } catch (PDOException $e) {
                            // column may not exist yet
                        }
                    }
                    $_SESSION['logged_in'] = true;
                    $_SESSION['username'] = $student['name_th'];
                    $_SESSION['user_id'] = $student['id'];
                    $_SESSION['student_code'] = $student['student_code'];
                    $_SESSION['role'] = 'student';
                    $_SESSION['curriculum_id'] = $student['curriculum_id'];
                    header('Location: ' . BASE_URL . '/index.php');
                    exit;
                }

                $error = 'ไม่พบอีเมล ' . htmlspecialchars($email) . ' ในระบบ กรุณาติดต่อผู้ดูแลระบบ';
            }
        }
    }
}

$_SESSION['google_login_error'] = $error;
header('Location: ' . BASE_URL . '/login.php');
exit;
