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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    cegic_json(['ok' => false, 'message' => 'Metodo no permitido.'], 405);
}

$raw = file_get_contents('php://input');
$json = json_decode($raw, true);

if (is_array($json)) {
    $user = isset($json['user']) ? trim($json['user']) : '';
    $password = isset($json['password']) ? trim($json['password']) : '';
} else {
    $user = isset($_POST['user']) ? trim($_POST['user']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
}

if ($user === '' || $password === '') {
    cegic_json(['ok' => false, 'message' => 'Usuario y contrasena requeridos.'], 400);
}

if (!isset($CEGIC_ACCOUNTS[$user])) {
    cegic_json(['ok' => false, 'message' => 'Usuario o contrasena incorrectos.'], 401);
}

$account = $CEGIC_ACCOUNTS[$user];
$realPassword = trim($account['password'] ?? '');

if ($realPassword !== $password) {
    cegic_json(['ok' => false, 'message' => 'Usuario o contrasena incorrectos.'], 401);
}

$_SESSION['cegic_user'] = $user;
$_SESSION['cegic_name'] = $account['name'] ?? $user;
$_SESSION['cegic_role'] = $account['role'] ?? 'committee';

cegic_json([
    'ok' => true,
    'user' => $user,
    'name' => $_SESSION['cegic_name'],
    'role' => $_SESSION['cegic_role']
]);