<?php
session_start();
if (!isset($_SESSION['logged_in'])) { header('Location: login.php'); exit; }
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

$agent_id  = (int)($_GET['agent_id'] ?? 0);
$date_from = $_GET['from'] ?? '';
$date_to   = $_GET['to'] ?? '';

$where = []; $params = [];
if ($agent_id > 0) { $where[] = "t.agent_id=?"; $params[] = $agent_id; }
if ($date_from) { $where[] = "t.trans_date>=?"; $params[] = $date_from; }
if ($date_to) { $where[] = "t.trans_date<=?"; $params[] = $date_to; }

$where_sql = $where ? "WHERE ".implode(" AND ",$where) : "";

$stmt = $pdo->prepare("
    SELECT t.*, a.name AS agent_name, s.bill_of_lading, s.container_count, s.item_description, 
           s.shipping_line, pol.hub_name AS pol_name, pod.hub_name AS pod_name,
           c.name AS customer_name, ct.container_type AS container_type_name
    FROM agent_transactions t
    LEFT JOIN agents a ON t.agent_id = a.agent_id
    LEFT JOIN newshipments s ON t.shipment_id = s.shipment_id
    LEFT JOIN container_types ct ON s.container_type_id = ct.container_id
    LEFT JOIN customers c ON s.customer_id = c.customer_id
    LEFT JOIN transport_hubs pol ON s.source_hub_id = pol.hub_id
    LEFT JOIN transport_hubs pod ON s.destination_hub_id = pod.hub_id
    $where_sql ORDER BY t.trans_date ASC, t.trans_id ASC
");
$stmt->execute($params);
$rows = $stmt->fetchAll();
$conf = $pdo->query("SELECT * FROM company_settings LIMIT 1")->fetch();
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <title>Agent Statement Print</title>
    <style>
        :root { --primary: #0f172a; --border: #cbd5e1; }
        body { font-family: 'Segoe UI', sans-serif; margin: 0; padding: 0; font-size: 10px; color: #1e293b; background: #f8fafc; }
        .settings-panel { background: #fff; padding: 15px 30px; border-bottom: 2px solid var(--primary); box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .checkbox-group { display: flex; gap: 10px; flex-wrap: wrap; }
        .checkbox-item { background: #f1f5f9; padding: 5px 10px; border-radius: 4px; cursor: pointer; border: 1px solid #e2e8f0; font-weight: 600; }
        .print-container { background: white; width: 277mm; margin: 20px auto; padding: 10mm; min-height: 180mm; box-shadow: 0 0 20px rgba(0,0,0,0.05); }
        .doc-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid var(--primary); padding-bottom: 10px; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; table-layout: fixed; }
        th, td { border: 1px solid var(--border); padding: 6px 4px; word-wrap: break-word; }
        th { background: #1e293b !important; color: white !important; font-size: 9px; -webkit-print-color-adjust: exact; }
        .amt { text-align: right; font-weight: 700; font-family: monospace; }
        .summary-box { margin-top: 20px; display: flex; justify-content: flex-end; }
        .summary-table { width: 280px; border: 2px solid var(--primary); }
        .summary-table td { padding: 6px; border: 1px solid #eee; }
        .doc-footer { margin-top: 40px; display: flex; justify-content: space-between; text-align: center; }
        .sig-line { width: 180px; border-top: 1px solid #000; padding-top: 5px; font-weight: bold; }
        @media print { .no-print { display: none !important; } .print-container { margin: 0; padding: 0; box-shadow: none; width: 100%; } @page { size: A4 landscape; margin: 10mm; } }
        .hide-col, .hide-summary { display: none !important; }
    </style>
</head>
<body>

<div class="settings-panel no-print">
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
        <h3 style="margin:0">Report Customization</h3>
        <button onclick="window.print()" style="background:#0f172a; color:white; border:none; padding:8px 20px; border-radius:4px; cursor:pointer;">Print Statement</button>
    </div>
    <div class="checkbox-group">
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(0)"> Date</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(1)"> B/L No</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(2)"> Customer</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(3)"> Route</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(4)"> Cont. Type</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(5)"> Cargo</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(6)"> Debit (-)</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(7)"> Credit (+)</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(8)"> Balance</label>
        <label class="checkbox-item" style="background:#e0f2fe;"><input type="checkbox" checked onchange="toggleSummary()"> Show Totals</label>
    </div>
</div>

<div class="print-container">
    <div class="doc-header">
        <div>
            <h2 style="margin:0;"><?= htmlspecialchars($conf['company_name_en']) ?></h2>
            <p style="font-size:9px; margin:2px 0;"><?= htmlspecialchars($conf['address_en']) ?></p>
        </div>
        <div style="text-align:right">
            <h2 style="margin:0; border-bottom:2px solid #0f172a;">AGENT STATEMENT</h2>
            <p style="margin:5px 0;">Agent: <strong><?= htmlspecialchars($rows[0]['agent_name'] ?? 'N/A') ?></strong></p>
        </div>
    </div>

    <table id="txnTable">
        <thead>
            <tr>
                <th width="65">Date</th>
                <th width="80">B/L Number</th>
                <th width="100">Customer</th>
                <th width="120">Route</th>
                <th width="80">Cont. Type</th>
                <th>Cargo Description</th>
                <th width="75">Debit (-)</th>
                <th width="75">Credit (+)</th>
                <th width="90">Balance</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $bal = 0; $t_deb = 0; $t_cre = 0;
            foreach($rows as $r): 
                $is_s = !empty($r['shipment_id']);
                $bal += ($r['credit'] - $r['debit']);
                $t_deb += $r['debit']; $t_cre += $r['credit'];
            ?>
            <tr>
                <td><?= $r['trans_date'] ?></td>
                <td><strong><?= $r['bill_of_lading'] ?: '-' ?></strong></td>
                <td><?= htmlspecialchars($r['customer_name'] ?: '-') ?></td>
                <td><?= $is_s ? $r['pol_name'].' &rarr; '.$r['pod_name'] : '-' ?></td>
                <td><?= $is_s ? $r['container_type_name'].' (x'.$r['container_count'].')' : '-' ?></td>
                <td><?= htmlspecialchars($is_s ? $r['item_description'] : $r['description']) ?></td>
                <td class="amt"><?= $r['debit'] > 0 ? number_format($r['debit'], 2) : '-' ?></td>
                <td class="amt"><?= $r['credit'] > 0 ? number_format($r['credit'], 2) : '-' ?></td>
                <td class="amt" style="background:#f8fafc;"><?= number_format($bal, 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="summary-box" id="summarySection">
        <table class="summary-table">
            <tr><td style="background:#f1f5f9; font-weight:bold;">Total Withdraw (Debit)</td><td class="amt"><?= number_format($t_deb, 2) ?></td></tr>
            <tr><td style="background:#f1f5f9; font-weight:bold;">Total Shipments (Credit)</td><td class="amt"><?= number_format($t_cre, 2) ?></td></tr>
            <tr style="background:var(--primary); color:white;">
                <td style="font-weight:bold;">NET CLOSING BALANCE</td>
                <td class="amt" style="color:white;"><?= number_format($bal, 2) ?> USD</td>
            </tr>
        </table>
    </div>
</div>

<script>
function toggleCol(index) {
    const table = document.getElementById('txnTable');
    for (let row of table.rows) { if (row.cells[index]) row.cells[index].classList.toggle('hide-col'); }
}
function toggleSummary() { document.getElementById('summarySection').classList.toggle('hide-summary'); }
</script>
</body>
</html>