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

// Logic to fetch data (same as previous)
$trans_type   = $_GET['trans_type'] ?? '';
$customer_id  = (int)($_GET['customer_id'] ?? 0);
$agent_id     = (int)($_GET['agent_id'] ?? 0);
$date_from    = $_GET['date_from'] ?? '';
$date_to      = $_GET['date_to'] ?? '';
$search_desc  = $_GET['search_desc'] ?? ''; 

$where = []; $params = [];
if ($trans_type !== '') { $where[] = 'd.trans_type = ?'; $params[] = $trans_type; }
if ($customer_id > 0) { $where[] = "(d.trans_type='customer' AND d.ref_id = ?)"; $params[] = $customer_id; }
if ($agent_id > 0) { $where[] = "(d.trans_type='agent' AND d.ref_id = ?)"; $params[] = $agent_id; }
if ($date_from && $date_to) { $where[] = 'd.trans_date BETWEEN ? AND ?'; $params[] = $date_from; $params[] = $date_to; }

if ($search_desc !== '') {
    $where[] = "(d.description LIKE ? OR s.bill_of_lading LIKE ? OR ct.container_type LIKE ? OR pol.hub_name LIKE ? OR pod.hub_name LIKE ?)";
    $sq = "%$search_desc%";
    $params = array_merge($params, [$sq, $sq, $sq, $sq, $sq]);
}

$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';
$stmt = $pdo->prepare("
    SELECT d.*, u.full_name AS user_name, c.name AS customer_name, a.name AS agent_name, e.expense_name, cb.cashbox_name,
           s.bill_of_lading, s.container_count, ct.container_type AS container_name, pol.hub_name AS pol_name, pod.hub_name AS pod_name
    FROM daily_transactions d
    LEFT JOIN users u ON d.user_id = u.user_id
    LEFT JOIN customers c ON d.trans_type='customer' AND d.ref_id = c.customer_id
    LEFT JOIN agents a    ON d.trans_type='agent'    AND d.ref_id = a.agent_id
    LEFT JOIN expenses e  ON d.trans_type='expense'  AND d.ref_id = e.expense_id
    LEFT JOIN cash_boxes cb ON d.trans_type='cash'   AND d.ref_id = cb.cashbox_id
    LEFT JOIN newshipments s ON d.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 d.trans_date ASC, d.daily_id ASC
");
$stmt->execute($params);
$rows = $stmt->fetchAll();

$total_debit = 0; $total_credit = 0; $running_balance = 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Print Statement - Ledger Details</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
        
        body { font-family: 'Inter', sans-serif; background: #fff; margin: 0; padding: 40px; color: #1e293b; line-height: 1.5; }
        
        /* Control Panel (Hidden on Print) */
        .no-print-zone {
            position: fixed; top: 0; right: 0; width: 260px; height: 100%; 
            background: #f1f5f9; border-left: 1px solid #e2e8f0; padding: 20px; box-sizing: border-box;
        }
        .btn-action {
            display: block; width: 100%; padding: 12px; border: none; border-radius: 6px;
            font-weight: 600; cursor: pointer; margin-bottom: 10px; text-align: center; text-decoration: none;
        }
        .btn-print { background: #0284c7; color: white; }
        .btn-close { background: #64748b; color: white; }

        /* Document Styling */
        .doc-wrapper { max-width: 1000px; margin: 0 auto; margin-right: 280px; } /* Space for sidebar */
        .header { display: flex; justify-content: space-between; align-items: flex-end; border-bottom: 3px solid #0f172a; padding-bottom: 15px; margin-bottom: 20px; }
        .header h1 { margin: 0; font-size: 24px; color: #0f172a; text-transform: uppercase; }
        .header-meta { text-align: right; font-size: 12px; }

        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th { background: #f8fafc; border: 1px solid #cbd5e1; padding: 10px; font-size: 11px; text-transform: uppercase; text-align: left; }
        td { border: 1px solid #cbd5e1; padding: 10px; font-size: 12px; vertical-align: top; }

        .logistics-details { font-size: 10px; background: #fdfdfd; padding: 5px; border: 1px dashed #e2e8f0; margin-top: 5px; color: #475569; }
        .money { font-family: 'Courier New', monospace; font-weight: 700; text-align: right; }
        
        .summary-container { display: flex; justify-content: flex-end; margin-top: 30px; }
        .summary-table { width: 300px; }
        .summary-table div { display: flex; justify-content: space-between; padding: 8px; border-bottom: 1px solid #e2e8f0; }
        .total-row { background: #0f172a; color: white; font-weight: bold; font-size: 14px; }

        .footer-sigs { margin-top: 80px; display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 50px; text-align: center; }
        .sig-box { border-top: 1px solid #333; padding-top: 10px; font-size: 12px; font-weight: bold; }

        @media print {
            .no-print-zone { display: none !important; }
            .doc-wrapper { margin-right: auto; width: 100%; }
            body { padding: 0; }
            th { background-color: #f8fafc !important; -webkit-print-color-adjust: exact; }
        }

        .hide-col { display: none !important; }
    </style>
</head>
<body>

<div class="no-print-zone">
    <h3 style="margin-top:0">Print Controls</h3>
    <p style="font-size: 11px; color: #64748b;">Show/Hide Columns:</p>
    <div style="font-size: 13px;">
        <label style="display:block; margin-bottom:5px;"><input type="checkbox" checked onchange="toggleCol(0)"> Date</label>
        <label style="display:block; margin-bottom:5px;"><input type="checkbox" checked onchange="toggleCol(1)"> Type</label>
        <label style="display:block; margin-bottom:5px;"><input type="checkbox" checked onchange="toggleCol(2)"> Entity</label>
        <label style="display:block; margin-bottom:5px;"><input type="checkbox" checked onchange="toggleCol(3)"> Description</label>
        <label style="display:block; margin-bottom:5px;"><input type="checkbox" checked onchange="toggleCol(4)"> Debit</label>
        <label style="display:block; margin-bottom:5px;"><input type="checkbox" checked onchange="toggleCol(5)"> Credit</label>
        <label style="display:block; margin-bottom:5px;"><input type="checkbox" checked onchange="toggleCol(6)"> Balance</label>
    </div>
    
    <button class="btn-action btn-print" onclick="window.print()">PRINT NOW</button>
    <a href="javascript:history.back()" class="btn-action btn-close">CANCEL / BACK</a>
</div>

<div class="doc-wrapper">
    <div class="header">
        <div>
            <h1>General Ledger Report</h1>
            <span style="font-size:12px; color:#64748b">Report Filtered by Selection</span>
        </div>
        <div class="header-meta">
            <b>Print Date:</b> <?= date('d-M-Y H:i') ?><br>
            <b>Period:</b> <?= $date_from ?: 'All' ?> to <?= $date_to ?: 'Present' ?>
        </div>
    </div>

    <table id="targetTable">
        <thead>
            <tr>
                <th>Date</th>
                <th>Type</th>
                <th>Entity / Reference</th>
                <th>Description & Logistics</th>
                <th style="text-align:right">Debit (+)</th>
                <th style="text-align:right">Credit (-)</th>
                <th style="text-align:right">Balance</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($rows as $r): 
                $total_debit += (float)$r['debit'];
                $total_credit += (float)$r['credit'];
                $running_balance += ((float)$r['debit'] - (float)$r['credit']);
            ?>
            <tr>
                <td><?= date('d/m/Y', strtotime($r['trans_date'])) ?></td>
                <td style="font-weight:bold; font-size:10px;"><?= strtoupper($r['trans_type']) ?></td>
                <td>
                    <b><?php
                        if($r['trans_type']=='customer') echo htmlspecialchars($r['customer_name']);
                        elseif($r['trans_type']=='agent') echo htmlspecialchars($r['agent_name']);
                        elseif($r['trans_type']=='expense') echo htmlspecialchars($r['expense_name']);
                        else echo htmlspecialchars($r['cashbox_name']);
                    ?></b>
                </td>
                <td>
                    <div style="font-weight:600;"><?= htmlspecialchars($r['description']) ?></div>
                    <?php if($r['shipment_id']): ?>
                        <div class="logistics-details">
                            <b>Route:</b> <?= $r['pol_name'] ?> → <?= $r['pod_name'] ?> | 
                            <b>B/L:</b> <?= $r['bill_of_lading'] ?><br>
                            <b>Container:</b> <?= $r['container_name'] ?> (Qty: <?= $r['container_count'] ?>)
                        </div>
                    <?php endif; ?>
                </td>
                <td class="money"><?= $r['debit'] > 0 ? number_format($r['debit'], 2) : '-' ?></td>
                <td class="money"><?= $r['credit'] > 0 ? number_format($r['credit'], 2) : '-' ?></td>
                <td class="money" style="background:#f8fafc;"><?= number_format($running_balance, 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="summary-container">
        <div class="summary-table">
            <div><span>Total Debits:</span> <span class="money"><?= number_format($total_debit, 2) ?></span></div>
            <div><span>Total Credits:</span> <span class="money"><?= number_format($total_credit, 2) ?></span></div>
            <div class="total-row"><span>Net Balance:</span> <span class="money"><?= number_format($running_balance, 2) ?></span></div>
        </div>
    </div>

    <div class="footer-sigs">
        <div class="sig-box">PREPARED BY</div>
        <div class="sig-box">ACCOUNTANT</div>
        <div class="sig-box">APPROVED BY</div>
    </div>
</div>

<script>
    function toggleCol(idx) {
        const table = document.getElementById('targetTable');
        const rows = table.rows;
        for (let i = 0; i < rows.length; i++) {
            rows[i].cells[idx].classList.toggle('hide-col');
        }
    }
</script>

</body>
</html>