<?php
/**
 * SAC 2026 - OWNER REPORT ENGINE v1.5
 * Arquitecto: Andres Mathison
 * Objetivo: Guardar reporte de pago en tabla payment_reports para validación administrativa.
 */
header('Content-Type: application/json');
require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

$user = checkSession();
if (!$user) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

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

$property_id = $user['property_id'] ?? $data['propertyId'] ?? null;
$property_code = $data['propertyCode'] ?? '';
$owner_name = $data['ownerName'] ?? '';
$amount_usd = $data['amountUsd'] ?? 0;
$amount_bs = $data['amountBs'] ?? 0;
$exchange_rate = $data['exchangeRate'] ?? 0;
$payment_date = $data['paymentDate'] ?? '';
$reference = $data['reference'] ?? '';
$bank_name = $data['bankName'] ?? '';
$method = $data['method'] ?? '';
$observations = $data['observations'] ?? '';

if (!$property_id || !$payment_date || !$reference) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required fields']);
    exit;
}

try {
    $pdo = getPDO();
    $stmt = $pdo->prepare("INSERT INTO payment_reports (property_id, property_code, owner_name, amount_usd, amount_bs, exchange_rate, payment_date, reference, bank_name, method, observations) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$property_id, $property_code, $owner_name, $amount_usd, $amount_bs, $exchange_rate, $payment_date, $reference, $bank_name, $method, $observations]);
    
    logSystemAction("REPORTÓ pago en espera para unidad ID: " . $property_id . " Ref: " . $reference, "PAGOS");
    
    echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>