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

session_start();

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

try {
    switch ($action) {
        case 'login':
            if ($method !== 'POST') {
                jsonResponse(['error' => 'Method not allowed'], 405);
            }
            
            $data = getJsonInput();
            $email = $data['email'] ?? '';
            $password = $data['password'] ?? '';
            
            if (empty($email) || empty($password)) {
                jsonResponse(['error' => 'Email e senha são obrigatórios'], 400);
            }
            
            $stmt = $pdo->prepare("SELECT * FROM administrators WHERE email = ? AND active = TRUE");
            $stmt->execute([$email]);
            $admin = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$admin || !password_verify($password, $admin['password'])) {
                jsonResponse(['error' => 'Email ou senha inválidos'], 401);
            }
            
            $_SESSION['admin_id'] = $admin['id'];
            $_SESSION['admin_name'] = $admin['name'];
            $_SESSION['admin_email'] = $admin['email'];
            $_SESSION['admin_color'] = $admin['color'];
            
            unset($admin['password']);
            jsonResponse(['success' => true, 'admin' => $admin]);
            break;
            
        case 'logout':
            session_destroy();
            jsonResponse(['success' => true]);
            break;
            
        case 'check':
            if (isset($_SESSION['admin_id'])) {
                $stmt = $pdo->prepare("SELECT id, name, email, color FROM administrators WHERE id = ?");
                $stmt->execute([$_SESSION['admin_id']]);
                $admin = $stmt->fetch(PDO::FETCH_ASSOC);
                jsonResponse(['authenticated' => true, 'admin' => $admin]);
            } else {
                jsonResponse(['authenticated' => false]);
            }
            break;
            
        case 'register':
            if ($method !== 'POST') {
                jsonResponse(['error' => 'Method not allowed'], 405);
            }
            
            $data = getJsonInput();
            $name = $data['name'] ?? '';
            $email = $data['email'] ?? '';
            $password = $data['password'] ?? '';
            $color = $data['color'] ?? '#3B82F6';
            
            if (empty($name) || empty($email) || empty($password)) {
                jsonResponse(['error' => 'Nome, email e senha são obrigatórios'], 400);
            }
            
            $checkStmt = $pdo->prepare("SELECT id FROM administrators WHERE email = ?");
            $checkStmt->execute([$email]);
            if ($checkStmt->fetch()) {
                jsonResponse(['error' => 'Email já cadastrado'], 400);
            }
            
            $id = bin2hex(random_bytes(18));
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO administrators (id, name, email, password, color, active) VALUES (?, ?, ?, ?, ?, TRUE)");
            $stmt->execute([$id, $name, $email, $hashedPassword, $color]);
            
            $stmt = $pdo->prepare("SELECT id, name, email, color, active, created_at FROM administrators WHERE id = ?");
            $stmt->execute([$id]);
            jsonResponse($stmt->fetch(), 201);
            break;
            
        default:
            jsonResponse(['error' => 'Action not specified'], 400);
    }
} catch (PDOException $e) {
    jsonResponse(['error' => 'Database error: ' . $e->getMessage()], 500);
}
