<?php
/**
 * SAC 2025 - MARK RECEIPT SENT
 * Actualiza el estado de envío de notificaciones en formato JSON.
 */
require_once 'config.php';

checkAccess(['admin', 'programmer', 'board']);

$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['feeId']) || !isset($data['propertyId']) || !isset($data['channel'])) {
    response(["error" => "Parámetros insuficientes"], 400);
}

try {
    // Obtener estado actual
    $stmt = $pdo->prepare("SELECT receipt_sent_json FROM property_debts WHERE fee_id = ? AND property_id = ?");
    $stmt->execute([$data['feeId'], $data['propertyId']]);
    $row = $stmt->fetch();

    $receiptStatus = json_decode($row['receipt_sent_json'] ?? '{}', true);
    
    // Actualizar el canal específico
    $receiptStatus[$data['channel']] = true;
    $receiptStatus['last_sent'] = date('Y-m-d H:i:s');

    $update = $pdo->prepare("UPDATE property_debts SET receipt_sent_json = ? WHERE fee_id = ? AND property_id = ?");
    $update->execute([json_encode($receiptStatus), $data['feeId'], $data['propertyId']]);

    response(["success" => true, "current_status" => $receiptStatus]);

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