<?php

// ============================================================
// config.php — Admin API RRB
// ============================================================

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

define('DB_HOST',    'localhost');
define('DB_NAME',    'wwsist_rrb5');
define('DB_USER',    'wwsist_mikes');
define('DB_PASS',    'Mikel123*');
define('ADMIN_SECRET_KEY', 'RRB_ADMIN_SECRET_2026_CAMBIAR');

// --- Funciones de base de datos ---

function getDB() {
    static $pdo = null;
    if ($pdo === null) {
        try {
            $pdo = new PDO(
                'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                ]
            );
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error de conexión a la base de datos.']);
            exit;
        }
    }
    return $pdo;
}

// --- Funciones de respuesta ---

function jsonOk($data, $code = 200) {
    http_response_code($code);
    echo json_encode(['success' => true, 'data' => $data], JSON_UNESCAPED_UNICODE);
    exit;
}

function jsonErr($code, $msg) {
    http_response_code($code);
    echo json_encode(['success' => false, 'message' => $msg], JSON_UNESCAPED_UNICODE);
    exit;
}

// --- Admin token management ---

function generateToken($adminId, $username) {
    $token = bin2hex(random_bytes(32));
    $db = getDB();
    
    $expira = date('Y-m-d H:i:s', time() + 86400 * 7); // 7 days
    
    $stmt = $db->prepare('INSERT INTO admin_sessions (idusuarios_sist, token, expira) VALUES (?, ?, ?)');
    $stmt->execute([$adminId, $token, $expira]);
    
    return $token;
}

function verifyToken($token) {
    $db = getDB();
    $stmt = $db->prepare('
        SELECT us.*, asess.token, asess.expira 
        FROM admin_sessions asess
        JOIN usuarios_sist us ON asess.idusuarios_sist = us.idusuarios_sist
        WHERE asess.token = ? AND asess.expira > NOW()
    ');
    $stmt->execute([$token]);
    return $stmt->fetch() ?: null;
}

function getAdminToken() {
    $h = '';
    
    if (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
        $h = $_SERVER['HTTP_AUTHORIZATION'];
    } elseif (!empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        $h = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    } elseif (function_exists('apache_request_headers')) {
        $hdrs = apache_request_headers();
        if (!empty($hdrs['Authorization'])) {
            $h = $hdrs['Authorization'];
        } elseif (!empty($hdrs['authorization'])) {
            $h = $hdrs['authorization'];
        }
    }
    
    if (!$h && function_exists('getallheaders')) {
        $hdrs = getallheaders();
        if (!empty($hdrs['Authorization'])) {
            $h = $hdrs['Authorization'];
        } elseif (!empty($hdrs['authorization'])) {
            $h = $hdrs['authorization'];
        }
    }
    
    if (!$h && !empty($_GET['token'])) {
        $h = 'Bearer ' . $_GET['token'];
    }
    
    if ($h && str_starts_with($h, 'Bearer ')) {
        return substr($h, 7);
    }
    
    return null;
}

function requireAdmin() {
    $token = getAdminToken();
    if (!$token) {
        jsonErr(401, 'Token requerido.');
    }
    
    $admin = verifyToken($token);
    if (!$admin) {
        jsonErr(401, 'Token inválido o expirado.');
    }
    
    return $admin;
}

// --- Leer body JSON ---

function body() {
    $raw = file_get_contents('php://input');
    $d   = json_decode($raw, true);
    return is_array($d) ? $d : [];
}

// --- Formatters ---

function formatMXN($amount) {
    return '$' . number_format($amount, 2, '.', ',');
}

function formatDate($date) {
    return date('d/m/Y', strtotime($date));
}

function formatDateTime($datetime) {
    return date('d/m/Y H:i', strtotime($datetime));
}

// ============================================================
// CORS y headers
// ============================================================
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
