<?php
/**
 * SAC 2026 - CONFIGURACIÓN CORE PRO v6.0
 * INCLUYE: MOTOR DE PROTECCIÓN SAAS (KILL-SWITCH)
 */

date_default_timezone_set('America/Caracas');

define('DOMAIN', 'https://condominios.microautomatismo.com');
define('BASE_PATH', '/CBO/SanDiego/AvDJC/UrbVDO/Tejar/');

// Cabeceras CORS
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $origin");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Accept, Origin");

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

header("Content-Type: application/json; charset=UTF-8");

// Captura de datos JSON
$RAW_INPUT = file_get_contents("php://input");
$REQUEST_DATA = json_decode($RAW_INPUT, true);

// Manejo de Sesión
if (PHP_VERSION_ID >= 70300) {
    session_set_cookie_params([
        'lifetime' => 86400, 'path' => '/', 'domain' => '', 
        'secure' => true, 'httponly' => true, 'samesite' => 'None',
    ]);
} else {
    session_set_cookie_params(86400, '/; SameSite=None; Secure', '', true, true);
}

if (session_status() === PHP_SESSION_NONE) { session_start(); }

// Conexión DB
$host = 'localhost'; 
$db   = 'microaut_cbosandiegoavdjcurbvdorotejar';
$user = 'microaut_amathison';
$pass = 'Info@2000';  

try {
     $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $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(["error" => "Error de Conexión"]);
     exit;
}

/**
 * MOTOR DE PROTECCIÓN SAAS (KILL-SWITCH)
 * Bloquea cualquier intento de escritura si la renta está vencida.
 */
function checkSystemIntegrity() {
    global $pdo;
    
    // El programador (Arquitecto) tiene Bypass para mantenimiento
    if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'programmer') return true;

    try {
        $stmt = $pdo->query("SELECT *, (expiration_date < CURDATE()) as is_expired FROM system_license WHERE id = 1");
        $license = $stmt->fetch();
        
        if ($license && ($license['is_blocked'] == 1 || $license['is_expired'] == 1)) {
            // Si el método es de escritura, bloquear drásticamente
            if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
                http_response_code(402); // Payment Required
                echo json_encode(["error" => "SYSTEM_LOCKED", "message" => "Renta de servicio SAC 2026 pendiente. Contacte a TecnoMath.com"]);
                exit;
            }
        }
    } catch (Exception $e) {}
}

// Ejecutar protección en cada llamado a la API
checkSystemIntegrity();

// Funciones Auxiliares
function response($data, $code = 200) {
    http_response_code($code);
    echo json_encode($data);
    exit;
}

function checkAccess($allowedRoles = ['admin', 'programmer', 'board']) {
    if (!isset($_SESSION['user_id'])) response(["error" => "No autorizado"], 401);
    if (!in_array($_SESSION['user_role'], $allowedRoles)) response(["error" => "Sin permisos"], 403);
}

function logSystemAction($action, $module) {
    global $pdo;
    if (!isset($_SESSION['user_id'])) return;
    try {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
        $stmt = $pdo->prepare("INSERT INTO system_audit_logs (user_id, username, user_role, action, module, ip_address, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$_SESSION['user_id'], $_SESSION['user_name'], $_SESSION['user_role'], $action, $module, $ip, date('Y-m-d H:i:s')]);
    } catch (Exception $e) {}
}

function getPDO() {
    global $pdo;
    return $pdo;
}

function checkSession() {
    if (!isset($_SESSION['user_id'])) return null;
    return [
        'id' => $_SESSION['user_id'],
        'role' => $_SESSION['user_role'],
        'name' => $_SESSION['user_name'],
        'property_id' => $_SESSION['property_id'] ?? null
    ];
}
?>