<?php
/**
 * SAC 2026 - ADVANCED LICENSE STATUS
 */
require_once 'config.php';

try {
    // 1. Obtener estatus maestro
    $stmt = $pdo->query("SELECT *, 
                        (expiration_date < CURDATE()) as is_expired 
                        FROM system_license WHERE id = 1");
    $license = $stmt->fetch();

    if (!$license) {
        $license = [
            'expiration_date' => date('Y-m-d', strtotime('+30 days')),
            'customer_name' => 'Condominio El Tejar',
            'is_expired' => 0,
            'is_blocked' => 0,
            'total_paid_to_date' => 0.00,
            'monthly_rate' => 40.00
        ];
    }

    // 2. Obtener historial de pagos de renta (TecnoMath)
    $stmtHistory = $pdo->query("SELECT * FROM system_license_payments ORDER BY payment_date DESC LIMIT 20");
    $history = $stmtHistory->fetchAll();

    $isBlocked = ($license['is_blocked'] == 1 || $license['is_expired'] == 1);
    
    response([
        "status" => $isBlocked ? "locked" : "active",
        "expiration_date" => $license['expiration_date'],
        "customer" => $license['customer_name'],
        "is_expired" => (bool)$license['is_expired'],
        "is_manual_block" => (bool)$license['is_blocked'],
        "total_paid" => (float)$license['total_paid_to_date'],
        "monthly_rate" => (float)$license['monthly_rate'],
        "payment_history" => $history
    ]);

} catch (PDOException $e) {
    response(["status" => "active", "is_blocked" => false]);
}
?>