<?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';

$customer_id = (int)($_GET['customer_id'] ?? 0);
$date_from   = $_GET['date_from'] ?? '';
$date_to     = $_GET['date_to'] ?? '';

$where = []; $params = [];
if ($customer_id > 0) { $where[] = 't.customer_id = ?'; $params[] = $customer_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.*, c.name AS customer_name, s.bill_of_lading, s.container_count, s.item_description, 
           s.departure_date, s.expected_arrival_date, s.shipping_line, 
           ct.container_type AS container_type_name, pol.hub_name AS pol_name, pod.hub_name AS pod_name
    FROM customer_transactions t
    JOIN customers c ON t.customer_id = c.customer_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 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
");
$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>Statement of Account</title>
    <style>
        :root { --primary: #0f172a; --border: #cbd5e1; }
        body { font-family: 'Segoe UI', Tahoma, 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; margin-bottom: 10px; }
        .checkbox-item { background: #f1f5f9; padding: 5px 10px; border-radius: 4px; cursor: pointer; border: 1px solid #e2e8f0; font-weight: 600; font-size: 11px; }
        
        .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; overflow: hidden; word-wrap: break-word; }
        th { background: #1e293b !important; color: white !important; font-size: 9px; -webkit-print-color-adjust: exact; }
        
        .row-shipment { background-color: #ffffff; }
        .row-payment { background-color: #f0fdf4; }
        .row-return { background-color: #fff1f2; }
        
        .amt { text-align: right; font-weight: 700; font-family: monospace; }
        
        /* Summary Box Styling */
        .summary-box { 
            margin-top: 20px; 
            display: flex; 
            justify-content: flex-end;
        }
        .summary-table { width: 300px; border: 2px solid var(--primary); }
        .summary-table td { padding: 8px; border: 1px solid #eee; font-size: 11px; }
        .summary-title { background: #f1f5f9; font-weight: bold; width: 150px; }
        .summary-total { background: var(--primary); color: white; font-size: 13px !important; }

        .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 {
            body { background: white; }
            .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)"> Route</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(3)"> Line</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 Desc.</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(6)"> Trans. Details</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(7)"> Debit</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(8)"> Credit</label>
        <label class="checkbox-item"><input type="checkbox" checked onchange="toggleCol(9)"> Balance</label>
        <label class="checkbox-item" style="background: #e0f2fe; border-color: #7dd3fc;"><input type="checkbox" checked onchange="toggleSummary()"> 📊 Show Totals Summary</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;">STATEMENT OF ACCOUNT</h2>
            <p style="margin:5px 0;">Customer: <strong><?= htmlspecialchars($rows[0]['customer_name'] ?? 'N/A') ?></strong></p>
        </div>
    </div>

    <table id="txnTable">
        <thead>
            <tr>
                <th width="65">Date</th>
                <th width="75">B/L Number</th>
                <th width="110">Route</th>
                <th width="75">Line</th>
                <th width="80">Cont. Type</th>
                <th>Cargo Description</th>
                <th>Transaction Details</th>
                <th width="70">Debit (+)</th>
                <th width="70">Credit (-)</th>
                <th width="85">Balance</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $bal = 0; $t_deb = 0; $t_cre = 0;
            foreach($rows as $r): 
                $is_s = !empty($r['shipment_id']);
                $row_cls = 'row-shipment';
                if (!$is_s) {
                    $row_cls = (strpos(strtolower($r['description']), 'return') !== false || strpos($r['description'], 'مرتجع') !== false) ? 'row-return' : 'row-payment';
                }
                $bal += ($r['debit'] - $r['credit']);
                $t_deb += $r['debit']; $t_cre += $r['credit'];
            ?>
            <tr class="<?= $row_cls ?>">
                <td><?= $r['trans_date'] ?></td>
                <td style="text-align:center"><strong><?= $r['bill_of_lading'] ?: '-' ?></strong></td>
                <td><?= $is_s ? $r['pol_name'].' &rarr; '.$r['pod_name'] : '-' ?></td>
                <td><?= $r['shipping_line'] ?: '-' ?></td>
                <td><?= $r['container_type_name'] ? $r['container_type_name'].' (x'.$r['container_count'].')' : '-' ?></td>
                <td style="font-size:9px;"><?= $is_s ? htmlspecialchars($r['item_description']) : '-' ?></td>
                <td style="font-size:9px; font-weight:bold;"><?= !$is_s ? htmlspecialchars($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 class="summary-title">Total Debit</td>
                <td class="amt"><?= number_format($t_deb, 2) ?></td>
            </tr>
            <tr>
                <td class="summary-title">Total Credit</td>
                <td class="amt"><?= number_format($t_cre, 2) ?></td>
            </tr>
            <tr class="summary-total">
                <td style="font-weight:bold;">NET BALANCE</td>
                <td class="amt" style="color:white;"><?= number_format($bal, 2) ?> USD</td>
            </tr>
        </table>
    </div>

    <div class="doc-footer">
        <div class="sig-line">Prepared By</div>
        <div class="sig-line">Audit Dept</div>
        <div class="sig-line">Customer Signature</div>
    </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>