<?php
header('Content-Type: application/json');
require_once 'config.php';

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

$property_id = $_GET['propertyId'] ?? null;

try {
    $pdo = getPDO();
    if ($property_id) {
        $stmt = $pdo->prepare("SELECT * FROM payment_reports WHERE property_id = ? ORDER BY created_at DESC");
        $stmt->execute([$property_id]);
    } else {
        if (!in_array($user['role'], ['admin', 'programmer', 'board'])) {
            http_response_code(403);
            echo json_encode(['error' => 'Forbidden']);
            exit;
        }
        $stmt = $pdo->query("SELECT * FROM payment_reports ORDER BY created_at DESC");
    }
    
    $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Map to camelCase for frontend
    $mapped = array_map(function($r) {
        return [
            'id' => (int)$r['id'],
            'propertyId' => (int)$r['property_id'],
            'propertyCode' => $r['property_code'],
            'ownerName' => $r['owner_name'],
            'amountUsd' => (float)$r['amount_usd'],
            'amountBs' => (float)$r['amount_bs'],
            'exchangeRate' => (float)$r['exchange_rate'],
            'paymentDate' => $r['payment_date'],
            'reference' => $r['reference'],
            'bankName' => $r['bank_name'],
            'method' => $r['method'],
            'status' => $r['status'],
            'observations' => $r['observations'],
            'createdAt' => $r['created_at'],
            'updatedAt' => $r['updated_at'],
            'assignedTo' => $r['assigned_to'],
            'targetId' => $r['target_id']
        ];
    }, $reports);
    
    echo json_encode($mapped);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>