<?php
/**
 * SAC 2026 - DUPLICATE REFERENCE CHECKER v1.0
 * Kernel V4.1.82 MC/MB
 */
require_once 'config.php';

$user = checkSession();
if (!$user) {
    response(["error" => "No autorizado"], 401);
}

$reference = $_GET['reference'] ?? '';

if (empty($reference) || $reference === 'S/R' || $reference === '0000') {
    response(["duplicate" => false]);
}

try {
    $pdo = getPDO();
    $results = [];

    // 1. Check in payment_reports (Pending/Approved reports)
    $stmt = $pdo->prepare("SELECT 'Reporte de Pago' as source, property_code as detail, payment_date as date, status FROM payment_reports WHERE reference = ? AND status != 'Rechazado' LIMIT 1");
    $stmt->execute([$reference]);
    if ($row = $stmt->fetch()) {
        $results[] = $row;
    }

    // 2. Check in payments (Registered fee payments)
    // We need to join with property_debts and properties to get the code
    $stmt = $pdo->prepare("
        SELECT 'Pago de Cuota' as source, pr.code as detail, p.payment_date as date 
        FROM payments p
        JOIN property_debts pd ON p.debt_id = pd.id
        JOIN properties pr ON pd.property_id = pr.id
        WHERE p.reference = ? 
        LIMIT 1
    ");
    $stmt->execute([$reference]);
    if ($row = $stmt->fetch()) {
        $results[] = $row;
    }

    // 3. Check in bank_transactions (Libro de Banco)
    $stmt = $pdo->prepare("SELECT 'Libro de Banco' as source, description as detail, date FROM bank_transactions WHERE reference = ? LIMIT 1");
    $stmt->execute([$reference]);
    if ($row = $stmt->fetch()) {
        $results[] = $row;
    }

    // 4. Check in pending_bills (Cuentas por Pagar)
    $stmt = $pdo->prepare("SELECT 'Cuenta por Pagar' as source, provider as detail, paid_date as date FROM pending_bills WHERE payment_reference = ? AND status = 'Pagado' LIMIT 1");
    $stmt->execute([$reference]);
    if ($row = $stmt->fetch()) {
        $results[] = $row;
    }

    if (count($results) > 0) {
        response([
            "duplicate" => true,
            "matches" => $results,
            "isAdmin" => in_array($user['role'], ['admin', 'programmer', 'board'])
        ]);
    } else {
        response(["duplicate" => false]);
    }

} catch (Exception $e) {
    response(["error" => $e->getMessage()], 500);
}
?>