<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Payments Report';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('money_fmt')) {
    function money_fmt($amount): string
    {
        return number_format((float)$amount, 2);
    }
}

if (!function_exists('payments_report_table_exists')) {
    function payments_report_table_exists(PDO $pdo, string $tableName): bool
    {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
        ");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

$errors = [];

$today = date('Y-m-d');
$monthStart = date('Y-m-01');

$dateFrom = trim((string)($_GET['date_from'] ?? $monthStart));
$dateTo = trim((string)($_GET['date_to'] ?? $today));
$selectedPropertyId = (int)($_GET['property_id'] ?? 0);
$selectedMethod = trim((string)($_GET['payment_method'] ?? ''));
$selectedAgentId = (int)($_GET['agent_id'] ?? 0);
$voidFilter = trim((string)($_GET['void_filter'] ?? 'active'));
$groupBy = trim((string)($_GET['group_by'] ?? 'method'));

$allowedVoidFilters = ['active', 'voided', 'all'];
if (!in_array($voidFilter, $allowedVoidFilters, true)) {
    $voidFilter = 'active';
}

$allowedGroupBy = ['method', 'date', 'property', 'agent', 'currency'];
if (!in_array($groupBy, $allowedGroupBy, true)) {
    $groupBy = 'method';
}

if ($dateFrom === '') {
    $dateFrom = $monthStart;
}
if ($dateTo === '') {
    $dateTo = $today;
}
if (strtotime($dateFrom) === false || strtotime($dateTo) === false) {
    $errors[] = 'Invalid date range selected.';
} elseif (strtotime($dateFrom) > strtotime($dateTo)) {
    $errors[] = 'Date from cannot be after date to.';
}

$requiredTables = ['payment', 'orders', 'properties'];
foreach ($requiredTables as $table) {
    if (!payments_report_table_exists($pdo, $table)) {
        $errors[] = 'Required table missing: ' . $table;
    }
}

$hasCurrencyTable = !$errors && payments_report_table_exists($pdo, 'tblcurrency');
$hasFolios = !$errors && payments_report_table_exists($pdo, 'folios') && payments_report_table_exists($pdo, 'folio_transactions');

$properties = [];
$agents = [];
$paymentMethods = [];
$currencies = [];

if (!$errors) {
    try {
        $properties = $pdo->query("
            SELECT id, name, code
            FROM properties
            WHERE is_active = 1
            ORDER BY name ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $errors[] = 'Could not load properties: ' . $e->getMessage();
    }

    try {
        $agents = $pdo->query("
            SELECT id, firstname, lastname
            FROM agents
            ORDER BY firstname ASC, lastname ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $agents = [];
    }

    try {
        $paymentMethods = $pdo->query("
            SELECT DISTINCT payment_method
            FROM payment
            WHERE payment_method IS NOT NULL AND payment_method <> ''
            ORDER BY payment_method ASC
        ")->fetchAll(PDO::FETCH_COLUMN);
    } catch (Throwable $e) {
        $paymentMethods = [];
    }

    if ($hasCurrencyTable) {
        try {
            $currencies = $pdo->query("
                SELECT CurrencyID, CurrencyCode, Currency, ROE
                FROM tblcurrency
                ORDER BY COALESCE(`order_no`, 999999), CurrencyCode ASC
            ")->fetchAll(PDO::FETCH_ASSOC);
        } catch (Throwable $e) {
            $currencies = [];
        }
    }
}

$currencyLabelSql = $hasCurrencyTable
    ? "COALESCE(NULLIF(c.CurrencyCode,''), CAST(pmt.currency AS CHAR), 'N/A')"
    : "COALESCE(CAST(pmt.currency AS CHAR), 'N/A')";

$where = "
    DATE(COALESCE(pmt.date_time, CONCAT(pmt.added_date, ' 00:00:00'))) BETWEEN :date_from AND :date_to
";
$params = [
    ':date_from' => $dateFrom,
    ':date_to'   => $dateTo,
];

if ($selectedPropertyId > 0) {
    $where .= " AND pmt.property_id = :property_id ";
    $params[':property_id'] = $selectedPropertyId;
}

if ($selectedMethod !== '') {
    $where .= " AND pmt.payment_method = :payment_method ";
    $params[':payment_method'] = $selectedMethod;
}

if ($selectedAgentId > 0) {
    $where .= " AND o.agent_id = :agent_id ";
    $params[':agent_id'] = $selectedAgentId;
}

if ($voidFilter === 'active') {
    $where .= " AND COALESCE(pmt.is_voided, 0) = 0 ";
} elseif ($voidFilter === 'voided') {
    $where .= " AND COALESCE(pmt.is_voided, 0) = 1 ";
}

$currencyJoin = $hasCurrencyTable
    ? " LEFT JOIN tblcurrency c ON c.CurrencyID = pmt.currency "
    : "";

$summary = [
    'payment_total' => 0,
    'active_total' => 0,
    'voided_total' => 0,
    'payment_count' => 0,
    'booking_count' => 0,
    'avg_payment' => 0,
];

$groupRows = [];
$dailyRows = [];
$methodRows = [];
$currencyRows = [];
$detailRows = [];
$voidedRows = [];

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                COALESCE(SUM(pmt.amount), 0) AS payment_total,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 0 THEN pmt.amount ELSE 0 END), 0) AS active_total,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 1 THEN pmt.amount ELSE 0 END), 0) AS voided_total,
                COUNT(*) AS payment_count,
                COUNT(DISTINCT pmt.order_id) AS booking_count,
                COALESCE(AVG(pmt.amount), 0) AS avg_payment
            FROM payment pmt
            LEFT JOIN orders o ON o.id = pmt.order_id
            LEFT JOIN properties pr ON pr.id = pmt.property_id
            $currencyJoin
            WHERE $where
        ");
        $stmt->execute($params);
        $summary = array_merge($summary, $stmt->fetch(PDO::FETCH_ASSOC) ?: []);
    } catch (Throwable $e) {
        $errors[] = 'Could not load payments summary: ' . $e->getMessage();
    }
}

if (!$errors) {
    try {
        switch ($groupBy) {
            case 'date':
                $groupSelect = "DATE(COALESCE(pmt.date_time, CONCAT(pmt.added_date, ' 00:00:00')))";
                break;
            case 'property':
                $groupSelect = "COALESCE(pr.name, 'No Property')";
                break;
            case 'agent':
                $groupSelect = "COALESCE(NULLIF(TRIM(CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,''))), ''), 'Direct / No Agent')";
                break;
            case 'currency':
                $groupSelect = $currencyLabelSql;
                break;
            case 'method':
            default:
                $groupSelect = "COALESCE(NULLIF(pmt.payment_method,''), 'Unspecified')";
                break;
        }

        $stmt = $pdo->prepare("
            SELECT
                $groupSelect AS group_label,
                COUNT(*) AS payment_count,
                COUNT(DISTINCT pmt.order_id) AS booking_count,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 0 THEN pmt.amount ELSE 0 END), 0) AS active_total,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 1 THEN pmt.amount ELSE 0 END), 0) AS voided_total,
                COALESCE(SUM(pmt.amount), 0) AS payment_total,
                COALESCE(AVG(pmt.amount), 0) AS avg_payment
            FROM payment pmt
            LEFT JOIN orders o ON o.id = pmt.order_id
            LEFT JOIN agents a ON a.id = o.agent_id
            LEFT JOIN properties pr ON pr.id = pmt.property_id
            $currencyJoin
            WHERE $where
            GROUP BY group_label
            ORDER BY active_total DESC, group_label ASC
        ");
        $stmt->execute($params);
        $groupRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $errors[] = 'Could not load grouped payments report: ' . $e->getMessage();
    }
}

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                DATE(COALESCE(pmt.date_time, CONCAT(pmt.added_date, ' 00:00:00'))) AS payment_date,
                COUNT(*) AS payment_count,
                COUNT(DISTINCT pmt.order_id) AS booking_count,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 0 THEN pmt.amount ELSE 0 END), 0) AS active_total,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 1 THEN pmt.amount ELSE 0 END), 0) AS voided_total,
                COALESCE(SUM(pmt.amount), 0) AS payment_total
            FROM payment pmt
            LEFT JOIN orders o ON o.id = pmt.order_id
            LEFT JOIN properties pr ON pr.id = pmt.property_id
            $currencyJoin
            WHERE $where
            GROUP BY payment_date
            ORDER BY payment_date ASC
        ");
        $stmt->execute($params);
        $dailyRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $dailyRows = [];
    }
}

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                COALESCE(NULLIF(pmt.payment_method,''), 'Unspecified') AS payment_method,
                COUNT(*) AS payment_count,
                COUNT(DISTINCT pmt.order_id) AS booking_count,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 0 THEN pmt.amount ELSE 0 END), 0) AS active_total,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 1 THEN pmt.amount ELSE 0 END), 0) AS voided_total
            FROM payment pmt
            LEFT JOIN orders o ON o.id = pmt.order_id
            LEFT JOIN properties pr ON pr.id = pmt.property_id
            $currencyJoin
            WHERE $where
            GROUP BY payment_method
            ORDER BY active_total DESC, payment_method ASC
        ");
        $stmt->execute($params);
        $methodRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $methodRows = [];
    }
}

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                $currencyLabelSql AS currency_label,
                COUNT(*) AS payment_count,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 0 THEN pmt.amount ELSE 0 END), 0) AS active_total,
                COALESCE(SUM(CASE WHEN COALESCE(pmt.is_voided,0) = 1 THEN pmt.amount ELSE 0 END), 0) AS voided_total
            FROM payment pmt
            LEFT JOIN orders o ON o.id = pmt.order_id
            LEFT JOIN properties pr ON pr.id = pmt.property_id
            $currencyJoin
            WHERE $where
            GROUP BY currency_label
            ORDER BY active_total DESC, currency_label ASC
        ");
        $stmt->execute($params);
        $currencyRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $currencyRows = [];
    }
}

if (!$errors) {
    try {
        $folioSelect = $hasFolios
            ? ",
                f.folio_name,
                f.folio_type"
            : ",
                NULL AS folio_name,
                NULL AS folio_type";

        $folioJoin = $hasFolios
            ? "
                LEFT JOIN folio_transactions ft ON ft.source_table = 'payment'
                    AND ft.source_id = pmt.id
                    AND ft.tx_type = 'payment'
                LEFT JOIN folios f ON f.id = ft.folio_id
              "
            : "";

        $stmt = $pdo->prepare("
            SELECT
                pmt.*,
                DATE(COALESCE(pmt.date_time, CONCAT(pmt.added_date, ' 00:00:00'))) AS payment_date,
                $currencyLabelSql AS currency_label,
                o.order_no,
                o.check_in,
                o.check_out,
                pr.name AS property_name,
                pr.code AS property_code,
                TRIM(CONCAT(COALESCE(g.firstname,''), ' ', COALESCE(g.lastname,''))) AS guest_name,
                TRIM(CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,''))) AS agent_name
                $folioSelect
            FROM payment pmt
            LEFT JOIN orders o ON o.id = pmt.order_id
            LEFT JOIN guests g ON g.id = o.guest_id
            LEFT JOIN agents a ON a.id = o.agent_id
            LEFT JOIN properties pr ON pr.id = pmt.property_id
            $currencyJoin
            $folioJoin
            WHERE $where
            ORDER BY COALESCE(pmt.date_time, CONCAT(pmt.added_date, ' 00:00:00')) DESC, pmt.id DESC
            LIMIT 1500
        ");
        $stmt->execute($params);
        $detailRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $errors[] = 'Could not load payment detail: ' . $e->getMessage();
    }
}

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                pmt.id,
                pmt.order_id,
                pmt.amount,
                pmt.payment_method,
                pmt.date_time,
                pmt.added_date,
                pmt.id_upload,
                pmt.void_reason,
                o.order_no,
                pr.name AS property_name,
                TRIM(CONCAT(COALESCE(g.firstname,''), ' ', COALESCE(g.lastname,''))) AS guest_name
            FROM payment pmt
            LEFT JOIN orders o ON o.id = pmt.order_id
            LEFT JOIN guests g ON g.id = o.guest_id
            LEFT JOIN properties pr ON pr.id = pmt.property_id
            WHERE $where
              AND COALESCE(pmt.is_voided, 0) = 1
            ORDER BY COALESCE(pmt.date_time, CONCAT(pmt.added_date, ' 00:00:00')) DESC, pmt.id DESC
            LIMIT 50
        ");
        $stmt->execute($params);
        $voidedRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $voidedRows = [];
    }
}

if (isset($_GET['export']) && $_GET['export'] === 'csv' && !$errors) {
    $filename = 'payments_report_' . date('Ymd_His') . '.csv';

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    $out = fopen('php://output', 'w');

    fputcsv($out, [
        'Date',
        'Property',
        'Booking',
        'Guest',
        'Agent',
        'Folio',
        'Folio Type',
        'Payment Method',
        'Reference',
        'Invoice',
        'Currency',
        'ROE',
        'Amount',
        'Voided',
        'Void Reason'
    ]);

    foreach ($detailRows as $row) {
        $property = trim((string)($row['property_name'] ?? ''));
        if (!empty($row['property_code'])) {
            $property .= ' (' . $row['property_code'] . ')';
        }

        fputcsv($out, [
            $row['payment_date'],
            $property,
            $row['order_no'] ?: ('#' . $row['order_id']),
            trim((string)$row['guest_name']),
            trim((string)$row['agent_name']),
            $row['folio_name'] ?? '',
            $row['folio_type'] ?? '',
            $row['payment_method'],
            $row['id_upload'],
            $row['invoice'],
            $row['currency_label'],
            $row['roe_atm'],
            number_format((float)$row['amount'], 2, '.', ''),
            !empty($row['is_voided']) ? 'Yes' : 'No',
            $row['void_reason'] ?? '',
        ]);
    }

    fclose($out);
    exit;
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50">
                <i class="bi bi-cash-stack"></i> Cash Control & Reconciliation
            </div>
            <div class="hero-title mt-2">Payments Report</div>
            <div class="hero-subtitle mt-2">
                Review payments by method, property, date, currency, agent and booking, with voided payment control.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="payments_report.php?<?php echo h(http_build_query(array_merge($_GET, ['export' => 'csv']))); ?>" class="btn btn-light">
                <i class="bi bi-download me-2"></i>Export CSV
            </a>
        </div>
    </div>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card panel-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-2">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Property</label>
                <select name="property_id" class="form-select">
                    <option value="0">All properties</option>
                    <?php foreach ($properties as $property): ?>
                        <option value="<?php echo (int)$property['id']; ?>" <?php echo $selectedPropertyId === (int)$property['id'] ? 'selected' : ''; ?>>
                            <?php echo h($property['name']); ?> - <?php echo h($property['code']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Method</label>
                <select name="payment_method" class="form-select">
                    <option value="">All methods</option>
                    <?php foreach ($paymentMethods as $method): ?>
                        <option value="<?php echo h($method); ?>" <?php echo $selectedMethod === (string)$method ? 'selected' : ''; ?>>
                            <?php echo h($method); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Agent</label>
                <select name="agent_id" class="form-select">
                    <option value="0">All agents / direct</option>
                    <?php foreach ($agents as $agent): ?>
                        <?php $agentName = trim(($agent['firstname'] ?? '') . ' ' . ($agent['lastname'] ?? '')); ?>
                        <option value="<?php echo (int)$agent['id']; ?>" <?php echo $selectedAgentId === (int)$agent['id'] ? 'selected' : ''; ?>>
                            <?php echo h($agentName !== '' ? $agentName : ('Agent #' . (int)$agent['id'])); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-1">
                <label class="form-label">Void</label>
                <select name="void_filter" class="form-select">
                    <option value="active" <?php echo $voidFilter === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="voided" <?php echo $voidFilter === 'voided' ? 'selected' : ''; ?>>Voided</option>
                    <option value="all" <?php echo $voidFilter === 'all' ? 'selected' : ''; ?>>All</option>
                </select>
            </div>

            <div class="col-md-1">
                <label class="form-label">Group</label>
                <select name="group_by" class="form-select">
                    <option value="method" <?php echo $groupBy === 'method' ? 'selected' : ''; ?>>Method</option>
                    <option value="date" <?php echo $groupBy === 'date' ? 'selected' : ''; ?>>Date</option>
                    <option value="property" <?php echo $groupBy === 'property' ? 'selected' : ''; ?>>Property</option>
                    <option value="agent" <?php echo $groupBy === 'agent' ? 'selected' : ''; ?>>Agent</option>
                    <option value="currency" <?php echo $groupBy === 'currency' ? 'selected' : ''; ?>>Currency</option>
                </select>
            </div>

            <div class="col-md-12 d-grid d-md-flex justify-content-md-end">
                <button class="btn btn-primary">
                    <i class="bi bi-funnel me-2"></i>Apply Filters
                </button>
            </div>
        </form>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-cash-stack"></i></div>
            <div>
                <div class="metric-label">Active Payments</div>
                <div class="metric-value"><?php echo money_fmt($summary['active_total']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-x-circle"></i></div>
            <div>
                <div class="metric-label">Voided</div>
                <div class="metric-value"><?php echo money_fmt($summary['voided_total']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-receipt"></i></div>
            <div>
                <div class="metric-label">Records</div>
                <div class="metric-value"><?php echo (int)$summary['payment_count']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-journal-check"></i></div>
            <div>
                <div class="metric-label">Bookings</div>
                <div class="metric-value"><?php echo (int)$summary['booking_count']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-calculator"></i></div>
            <div>
                <div class="metric-label">Average</div>
                <div class="metric-value"><?php echo money_fmt($summary['avg_payment']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-secondary-subtle text-secondary"><i class="bi bi-wallet2"></i></div>
            <div>
                <div class="metric-label">Gross Total</div>
                <div class="metric-value"><?php echo money_fmt($summary['payment_total']); ?></div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-7">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Grouped Payment Summary</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Group</th>
                                <th class="text-end">Bookings</th>
                                <th class="text-end">Records</th>
                                <th class="text-end">Active</th>
                                <th class="text-end">Voided</th>
                                <th class="text-end">Average</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$groupRows): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No payment data found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($groupRows as $row): ?>
                                    <tr>
                                        <td><strong><?php echo h($row['group_label']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['booking_count']; ?></td>
                                        <td class="text-end"><?php echo (int)$row['payment_count']; ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['active_total']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['voided_total']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['avg_payment']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-5">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Payments by Method</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Method</th>
                                <th class="text-end">Records</th>
                                <th class="text-end">Active</th>
                                <th class="text-end">Voided</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$methodRows): ?>
                                <tr><td colspan="4" class="text-center text-muted py-4">No methods found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($methodRows as $row): ?>
                                    <tr>
                                        <td><strong><?php echo h($row['payment_method']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['payment_count']; ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['active_total']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['voided_total']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Daily Reconciliation</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th class="text-end">Bookings</th>
                                <th class="text-end">Records</th>
                                <th class="text-end">Active</th>
                                <th class="text-end">Voided</th>
                                <th class="text-end">Gross</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$dailyRows): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No daily payments found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($dailyRows as $row): ?>
                                    <tr>
                                        <td><strong><?php echo h($row['payment_date']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['booking_count']; ?></td>
                                        <td class="text-end"><?php echo (int)$row['payment_count']; ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['active_total']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['voided_total']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['payment_total']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-5">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Payments by Currency</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Currency</th>
                                <th class="text-end">Records</th>
                                <th class="text-end">Active</th>
                                <th class="text-end">Voided</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$currencyRows): ?>
                                <tr><td colspan="4" class="text-center text-muted py-4">No currency data found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($currencyRows as $row): ?>
                                    <tr>
                                        <td><strong><?php echo h($row['currency_label']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['payment_count']; ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['active_total']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['voided_total']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <?php if ($voidedRows): ?>
    <div class="col-12">
        <div class="card panel-card">
            <div class="card-header">
                <h5 class="mb-0">Recent Voided Payments</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Property</th>
                                <th>Booking</th>
                                <th>Guest</th>
                                <th>Method</th>
                                <th>Reference</th>
                                <th>Reason</th>
                                <th class="text-end">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($voidedRows as $row): ?>
                                <tr class="table-secondary">
                                    <td><?php echo h($row['date_time'] ?: $row['added_date']); ?></td>
                                    <td><?php echo h($row['property_name'] ?: 'Not set'); ?></td>
                                    <td><?php echo h($row['order_no'] ?: ('#' . $row['order_id'])); ?></td>
                                    <td><?php echo h(trim((string)$row['guest_name']) ?: 'Guest'); ?></td>
                                    <td><?php echo h($row['payment_method']); ?></td>
                                    <td><?php echo h($row['id_upload']); ?></td>
                                    <td><?php echo h($row['void_reason']); ?></td>
                                    <td class="text-end fw-bold"><?php echo money_fmt($row['amount']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="col-12">
        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Payment Detail</h5>
                <span class="text-muted small">Showing latest 1,500 payments</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Property</th>
                                <th>Booking</th>
                                <th>Guest</th>
                                <th>Agent</th>
                                <th>Folio</th>
                                <th>Method</th>
                                <th>Reference</th>
                                <th>Currency</th>
                                <th class="text-end">Amount</th>
                                <th>Status</th>
                                <th class="text-end">Links</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$detailRows): ?>
                                <tr><td colspan="12" class="text-center text-muted py-4">No payments found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($detailRows as $row): ?>
                                    <?php
                                    $propertyLabel = trim((string)($row['property_name'] ?? ''));
                                    if (!empty($row['property_code'])) {
                                        $propertyLabel .= ' (' . $row['property_code'] . ')';
                                    }
                                    $guestName = trim((string)($row['guest_name'] ?? ''));
                                    $agentName = trim((string)($row['agent_name'] ?? ''));
                                    $isVoided = !empty($row['is_voided']);
                                    ?>
                                    <tr class="<?php echo $isVoided ? 'table-secondary' : ''; ?>">
                                        <td><?php echo h($row['payment_date']); ?></td>
                                        <td><?php echo h($propertyLabel ?: 'Not set'); ?></td>
                                        <td>
                                            <a href="/rooms/modules/payments/payments.php?order_id=<?php echo (int)$row['order_id']; ?>" class="booking-ref">
                                                <?php echo h($row['order_no'] ?: ('#' . $row['order_id'])); ?>
                                            </a>
                                        </td>
                                        <td><?php echo h($guestName ?: 'Guest'); ?></td>
                                        <td><?php echo h($agentName ?: 'Direct'); ?></td>
                                        <td>
                                            <div class="data-stack">
                                                <strong><?php echo h($row['folio_name'] ?: 'Master / Not mapped'); ?></strong>
                                                <small><?php echo h($row['folio_type'] ?: ''); ?></small>
                                            </div>
                                        </td>
                                        <td><?php echo h($row['payment_method']); ?></td>
                                        <td><?php echo h($row['id_upload']); ?></td>
                                        <td><?php echo h($row['currency_label']); ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['amount']); ?></td>
                                        <td>
                                            <?php if ($isVoided): ?>
                                                <span class="badge text-bg-danger">Voided</span>
                                                <?php if (!empty($row['void_reason'])): ?>
                                                    <div class="small text-danger mt-1"><?php echo h($row['void_reason']); ?></div>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="badge text-bg-success">Active</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="d-inline-flex gap-2 justify-content-end">
                                                <a href="/rooms/modules/payments/payments.php?order_id=<?php echo (int)$row['order_id']; ?>"
                                                   class="btn btn-sm btn-outline-primary">
                                                    View
                                                </a>
                                                <a href="/rooms/modules/payments/receipt.php?order_id=<?php echo (int)$row['order_id']; ?>&payment_id=<?php echo (int)$row['id']; ?>"
                                                   class="btn btn-sm btn-outline-success"
                                                   target="_blank">
                                                    Receipt
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
