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

/* الصلاحيات */
if (!can('daily_transactions','view')) {
    die('Access Denied');
}

/* 1. استقبال الفلاتر المتقدمة */
$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) : '';

/* رابط الطباعة مع تمرير الفلاتر */
$print_url = "daily_transactions_print.php?" . http_build_query($_GET);

/* 2. جلب البيانات */
$customers_list = $pdo->query("SELECT customer_id, name FROM customers ORDER BY name ASC")->fetchAll();
$agents_list    = $pdo->query("SELECT agent_id, name FROM agents ORDER BY name ASC")->fetchAll();

$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" dir="ltr">
<head>
    <meta charset="UTF-8">
    <title>Daily Transactions | Advanced Ledger</title>
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/select2.min.css">
    <style>
        :root { --primary: #1e293b; --accent: #0284c7; --success: #10b981; --danger: #ef4444; --bg: #f1f5f9; --border: #e2e8f0; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); color: #334155; margin: 0; padding: 20px; font-size: 13px; }
        
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .btn { padding: 10px 18px; border-radius: 8px; font-weight: 600; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; border: none; cursor: pointer; transition: 0.3s; }
        .btn-back { background: #64748b; color: white; }
        .btn-print { background: var(--accent); color: white; }

        .filter-card { background: white; padding: 20px; border-radius: 12px; border: 1px solid var(--border); margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; align-items: end; }
        .filter-group { display: flex; flex-direction: column; gap: 5px; }
        .filter-group label { font-size: 10px; font-weight: 800; color: #64748b; text-transform: uppercase; }
        .filter-group select, .filter-group input { padding: 8px; border: 1px solid var(--border); border-radius: 6px; }

        .main-card { background: white; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); border: 1px solid var(--border); overflow: hidden; }
        table { width: 100%; border-collapse: collapse; }
        th { background: var(--primary); color: white; padding: 12px; font-size: 10px; text-transform: uppercase; text-align: left; }
        td { padding: 12px; border-bottom: 1px solid #f1f5f9; vertical-align: top; }

        .logistics-box { background: #f8fafc; border: 1px dashed var(--border); padding: 5px 8px; border-radius: 6px; margin-top: 5px; font-size: 11px; }
        .route-tag { color: var(--accent); font-weight: 700; }
        .container-tag { background: #e2e8f0; padding: 2px 5px; border-radius: 4px; font-weight: 600; font-size: 10px; }

        .badge { padding: 3px 7px; border-radius: 4px; font-size: 9px; font-weight: 800; text-transform: uppercase; display: inline-flex; align-items: center; gap: 3px; }
        .badge-customer { background: #e0f2fe; color: #0369a1; }
        .badge-agent { background: #fef3c7; color: #92400e; }
        .badge-expense { background: #fee2e2; color: #991b1b; }
        
        .money { font-family: 'Roboto Mono', monospace; font-weight: 700; text-align: right; white-space: nowrap; }
        .debit { color: var(--danger); }
        .credit { color: var(--success); }
        .balance-col { background: #f8fafc; font-weight: 800; border-left: 1px solid var(--border); }

        .summary-footer { background: var(--primary); color: white; padding: 20px; display: flex; justify-content: flex-end; gap: 40px; }
    </style>
</head>
<body>

<div class="page-header">
    <h2><i class="fas fa-list-alt" style="color:var(--accent)"></i> General Ledger & Logistics Details</h2>
    <div style="display:flex; gap:10px;">
        <a href="dashboard.php" class="btn btn-back"><i class="fas fa-arrow-left"></i> Back</a>
        <a href="<?= $print_url ?>" class="btn btn-print"><i class="fas fa-print"></i> Go to Print Page</a>
    </div>
</div>

<form method="get" class="filter-card">
    <div class="filter-grid">
        <div class="filter-group">
            <label>Search (Desc, B/L, Container, Port)</label>
            <input type="text" name="search_desc" placeholder="Search anything..." value="<?= htmlspecialchars($search_desc) ?>">
        </div>
        <div class="filter-group">
            <label>Type</label>
            <select name="trans_type">
                <option value="">All</option>
                <option value="customer" <?= $trans_type=='customer'?'selected':'' ?>>Customer</option>
                <option value="agent" <?= $trans_type=='agent'?'selected':'' ?>>Agent</option>
                <option value="expense" <?= $trans_type=='expense'?'selected':'' ?>>Expense</option>
            </select>
        </div>
        <div class="filter-group">
            <label>Customer</label>
            <select name="customer_id" class="select2">
                <option value="">Choose...</option>
                <?php foreach($customers_list as $c): ?>
                    <option value="<?= $c['customer_id'] ?>" <?= $customer_id==$c['customer_id']?'selected':'' ?>><?= htmlspecialchars($c['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="filter-group">
            <label>From</label>
            <input type="date" name="date_from" value="<?= $date_from ?>">
        </div>
        <div class="filter-group">
            <label>To</label>
            <input type="date" name="date_to" value="<?= $date_to ?>">
        </div>
        <button type="submit" class="btn btn-print" style="height:35px;"><i class="fas fa-search"></i> Filter</button>
    </div>
</form>

<div class="main-card">
    <table>
        <thead>
            <tr>
                <th width="90">Date</th>
                <th width="100">Type</th>
                <th width="180">Entity / Reference</th>
                <th>Description & Shipment Details</th>
                <th width="100" style="text-align:right">Debit (+)</th>
                <th width="100" style="text-align:right">Credit (-)</th>
                <th width="110" 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']);
                $type = $r['trans_type'];
            ?>
            <tr>
                <td><b><?= $r['trans_date'] ?></b><br><small style="color:#94a3b8">#<?= $r['daily_id'] ?></small></td>
                <td>
                    <span class="badge badge-<?= $type ?>">
                        <?= strtoupper($type) ?>
                    </span>
                </td>
                <td>
                    <div style="font-weight:700;">
                        <?php
                            if($type=='customer') echo htmlspecialchars($r['customer_name']);
                            elseif($type=='agent') echo htmlspecialchars($r['agent_name']);
                            elseif($type=='expense') echo htmlspecialchars($r['expense_name']);
                            else echo htmlspecialchars($r['cashbox_name']);
                        ?>
                    </div>
                    <small style="color:#94a3b8">User: <?= htmlspecialchars($r['user_name']) ?></small>
                </td>
                <td>
                    <div style="color:#475569; font-weight:500;"><?= htmlspecialchars($r['description']) ?></div>
                    
                    <?php if($r['shipment_id']): ?>
                    <div class="logistics-box">
                        <div style="margin-bottom:3px;">
                            <span class="route-tag"><?= $r['pol_name'] ?> <i class="fas fa-long-arrow-alt-right"></i> <?= $r['pod_name'] ?></span>
                            | B/L: <b><?= $r['bill_of_lading'] ?></b>
                        </div>
                        <div>
                            <span class="container-tag"><i class="fas fa-box"></i> <?= $r['container_name'] ?></span>
                            <span style="margin-left:5px;">Qty: <b><?= $r['container_count'] ?></b></span>
                        </div>
                    </div>
                    <?php endif; ?>
                </td>
                <td class="money debit"><?= $r['debit'] > 0 ? number_format($r['debit'],2) : '-' ?></td>
                <td class="money credit"><?= $r['credit'] > 0 ? number_format($r['credit'],2) : '-' ?></td>
                <td class="money balance-col"><?= number_format($running_balance,2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="summary-footer">
        <div style="text-align:right"><label style="font-size:9px; color:#94a3b8">TOTAL DEBITS</label><br><b><?= number_format($total_debit,2) ?></b></div>
        <div style="text-align:right"><label style="font-size:9px; color:#94a3b8">TOTAL CREDITS</label><br><b><?= number_format($total_credit,2) ?></b></div>
        <div style="text-align:right; border-left:1px solid #475569; padding-left:30px;"><label style="font-size:9px; color:#94a3b8">NET BALANCE</label><br><b style="color:#38bdf8"><?= number_format($running_balance,2) ?></b></div>
    </div>
</div>

<script src="../assets/js/jquery-3.6.0.min.js"></script>
<script src="../assets/js/select2.min.js"></script>
<script>
    $(document).ready(function() { $('.select2').select2({ width: '100%' }); });
</script>
</body>
</html>