<?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('agent_transactions', 'view')) { die('Access Denied'); }

$agent_id     = (int)($_GET['agent_id'] ?? 0);
$date_from    = $_GET['from'] ?? '';
$date_to      = $_GET['to'] ?? '';
$search_query = $_GET['search_query'] ?? ''; // حقل البحث الجديد

$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; }

if (!empty($search_query)) {
    $where[] = "(s.bill_of_lading LIKE ? 
                OR pol.hub_name LIKE ? 
                OR pod.hub_name LIKE ? 
                OR s.shipping_line LIKE ? 
                OR c.name LIKE ?
                OR ct.container_type LIKE ?
                OR s.item_description LIKE ?)";
    $sq = "%$search_query%";
    $params = array_merge($params, [$sq, $sq, $sq, $sq, $sq, $sq, $sq]);
}

$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.agent_cost AS unit_price,
           s.item_description, s.shipment_details, s.factory_address,
           s.departure_date, s.expected_arrival_date, s.shipping_line,
           c.name AS customer_name,
           ct.container_type AS container_type_name,
           pol.hub_name AS pol_name, pod.hub_name AS pod_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();
$agents = $pdo->query("SELECT agent_id, name FROM agents WHERE status='active' ORDER BY name ASC")->fetchAll();

$total_debit = 0; $total_credit = 0; $running_balance = 0; 
$print_url = "agent_transactions_print.php?" . http_build_query($_GET);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <title>Agent Account 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); margin: 0; padding: 20px; font-size: 13px; }
        .main-card { background: white; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); border: 1px solid var(--border); margin-bottom: 20px; overflow: hidden; }
        table { width: 100%; border-collapse: collapse; }
        th { background: #f8fafc; color: #64748b; padding: 12px 15px; font-size: 11px; text-transform: uppercase; border-bottom: 2px solid var(--border); text-align: left; }
        td { padding: 15px; border-bottom: 1px solid var(--border); vertical-align: top; }
        .row-shipment { background-color: #f0f9ff44; }
        .bl-box { background: var(--primary); color: white; padding: 2px 8px; border-radius: 4px; font-family: monospace; font-size: 11px; }
        .route-flow { display: flex; align-items: center; gap: 8px; font-size: 11px; font-weight: 600; color: var(--primary); }
        .info-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-top: 10px; }
        .info-card { background: #f8fafc; border: 1px solid var(--border); padding: 6px; border-radius: 6px; }
        .info-card label { display: block; font-size: 9px; color: #94a3b8; font-weight: 700; text-transform: uppercase; }
        .amt { font-family: monospace; font-weight: 700; text-align: right; }
        .summary-footer { background: var(--primary); color: white; padding: 20px; display: flex; justify-content: flex-end; gap: 40px; }
        .search-input { padding: 8px 12px; border-radius: 6px; border: 1px solid var(--border); width: 100%; transition: all 0.3s; }
        .search-input:focus { border-color: var(--accent); outline: none; box-shadow: 0 0 0 3px rgba(2, 132, 199, 0.1); }
    </style>
</head>
<body>

<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
    <h2 style="margin:0;"><i class="fas fa-user-tie" style="color:var(--accent)"></i> Agent Statement</h2>
    <div style="display:flex; gap:10px;">
        <a href="dashboard.php" style="background:#64748b; color:white; padding:10px 15px; border-radius:8px; text-decoration:none;"><i class="fas fa-arrow-left"></i> Back</a>
        <a href="<?= $print_url ?>" target="_blank" style="background:var(--accent); color:white; padding:10px 15px; border-radius:8px; text-decoration:none;"><i class="fas fa-print"></i> Print Statement</a>
    </div>
</div>

<form method="GET" class="main-card" style="padding:20px; display:flex; gap:15px; align-items:flex-end; flex-wrap: wrap;">
    <div style="flex:1; min-width: 200px;">
        <label style="font-size:12px; font-weight:700;">Select Agent</label>
        <select name="agent_id" class="select2" style="width:100%">
            <option value="">All Agents</option>
            <?php foreach($agents as $a): ?>
                <option value="<?= $a['agent_id'] ?>" <?= $agent_id==$a['agent_id']?'selected':'' ?>><?= htmlspecialchars($a['name']) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <div style="flex:1; min-width: 200px;">
        <label style="font-size:12px; font-weight:700;">Search (B/L, Customer, Port, Cargo)</label>
        <input type="text" name="search_query" value="<?= htmlspecialchars($search_query) ?>" class="search-input" placeholder="Enter keywords...">
    </div>
    <input type="date" name="from" value="<?= $date_from ?>" style="padding:8px; border-radius:5px; border:1px solid var(--border)">
    <input type="date" name="to" value="<?= $date_to ?>" style="padding:8px; border-radius:5px; border:1px solid var(--border)">
    <button type="submit" style="background:var(--primary); color:white; padding:10px 25px; border:none; border-radius:5px; cursor:pointer; font-weight:600;">Filter</button>
</form>

<div class="main-card">
    <table>
        <thead>
            <tr>
                <th width="100">Date</th>
                <th>Details & Logistics</th>
                <th width="120" style="text-align:right">Debit (Out)</th>
                <th width="120" style="text-align:right">Credit (In)</th>
                <th width="130" style="text-align:right">Balance</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($rows as $r): 
                $is_s = !empty($r['shipment_id']);
                $total_debit += $r['debit']; $total_credit += $r['credit'];
                $running_balance += ($r['credit'] - $r['debit']);
            ?>
            <tr class="<?= $is_s ? 'row-shipment' : '' ?>">
                <td><b><?= $r['trans_date'] ?></b><br><small>#<?= $r['trans_id'] ?></small></td>
                <td>
                    <?php if($is_s): ?>
                        <div style="margin-bottom:5px;">
                            <span class="bl-box">B/L: <?= $r['bill_of_lading'] ?></span>
                            <strong style="margin-left:10px; color:var(--accent)"><?= htmlspecialchars($r['customer_name']) ?></strong>
                            <span style="margin-left:10px; font-weight:bold; color:#1e293b;">- <?= htmlspecialchars($r['item_description']) ?></span>
                        </div>
                        <div class="route-flow">
                            <span><i class="fas fa-ship"></i> <?= $r['pol_name'] ?></span>
                            <i class="fas fa-arrow-right" style="color:#cbd5e1"></i>
                            <span><i class="fas fa-map-marker-alt"></i> <?= $r['pod_name'] ?></span>
                        </div>
                        <div class="info-grid">
                            <div class="info-card"><label>Container Type</label><span><?= $r['container_type_name'] ?: 'N/A' ?></span></div>
                            <div class="info-card"><label>Qty</label><span><?= $r['container_count'] ?> Unit(s)</span></div>
                            <div class="info-card"><label>Line</label><span><?= $r['shipping_line'] ?: 'Direct' ?></span></div>
                            <div class="info-card" style="border-left:2px solid var(--success)"><label>Schedule</label><span style="font-size:10px">ETD: <?= $r['departure_date'] ?: '-' ?></span></div>
                        </div>
                    <?php else: ?>
                        <div style="color:var(--danger); font-weight:bold;"><i class="fas fa-money-bill-wave"></i> Financial Entry</div>
                        <div style="color:#64748b; font-size:12px;"><?= htmlspecialchars($r['description']) ?></div>
                    <?php endif; ?>
                </td>
                <td class="amt" style="color:var(--danger)"><?= $r['debit'] > 0 ? number_format($r['debit'],2) : '-' ?></td>
                <td class="amt" style="color:var(--success)"><?= $r['credit'] > 0 ? number_format($r['credit'],2) : '-' ?></td>
                <td class="amt" style="background:#f8fafc"><?= number_format($running_balance, 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <div class="summary-footer">
        <div style="text-align:right"><label style="font-size:10px; color:#94a3b8">TOTAL WITHDRAW</label><div style="font-size:18px; font-weight:800;"><?= number_format($total_debit, 2) ?></div></div>
        <div style="text-align:right"><label style="font-size:10px; color:#94a3b8">TOTAL CREDIT</label><div style="font-size:18px; font-weight:800; color:var(--success)"><?= number_format($total_credit, 2) ?></div></div>
        <div style="text-align:right; border-left:1px solid #475569; padding-left:30px;"><label style="font-size:10px; color:#94a3b8">NET BALANCE</label><div style="font-size:18px; font-weight:800; color:#38bdf8"><?= number_format($running_balance, 2) ?></div></div>
    </div>
</div>

<script src="../assets/js/jquery-3.6.0.min.js"></script>
<script src="../assets/js/select2.min.js"></script>
<script>$('.select2').select2({ placeholder: "Search for agent..." });</script>
</body>
</html>