<?php
require_once '../includes/db_connect.php';

// Start session securely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

if ($method === 'POST' && $action === 'login') {
    handleLogin($pdo);
} elseif ($method === 'POST' && $action === 'logout') {
    handleLogout();
} elseif ($method === 'GET' && $action === 'check') {
    handleCheck();
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request']);
}

function handleLogin($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);
    $email = $data['email'] ?? '';
    $password = $data['password'] ?? '';

    if (!$email || !$password) {
        http_response_code(400);
        echo json_encode(['error' => 'Email and password required']);
        return;
    }

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

    if ($user && password_verify($password, $user['password_hash'])) {
        // Login Success
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['user_avatar'] = $user['avatar_url'] ?? getInitials($user['name']);

        echo json_encode(['message' => 'Login successful', 'redirect' => 'dashboard.html']);
    } else {
        // Login Failed
        http_response_code(401);
        echo json_encode(['error' => 'Invalid credentials']);
    }
}

function handleLogout() {
    session_destroy();
    echo json_encode(['message' => 'Logged out', 'redirect' => 'login.html']);
}

function handleCheck() {
    if (isset($_SESSION['user_id'])) {
        echo json_encode([
            'authenticated' => true,
            'user' => [
                'name' => $_SESSION['user_name'],
                'role' => $_SESSION['user_role'],
                'email' => $_SESSION['user_email']
            ]
        ]);
    } else {
        http_response_code(401);
        echo json_encode(['authenticated' => false]);
    }
}

function getInitials($name) {
    return strtoupper(substr($name, 0, 2));
}
?>
