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

/* 1. استقبال الفلاتر */
$customer_id  = (int)($_GET['customer_id'] ?? 0);
$date_from    = $_GET['date_from'] ?? '';
$date_to      = $_GET['date_to'] ?? '';
$search_query = $_GET['search_query'] ?? ''; // حقل البحث الجديد

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

// منطق البحث في تفاصيل الشحنة (Detailed Shipment Info)
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 ct.container_type LIKE ?
                OR s.item_description LIKE ?)";
    $sq = "%$search_query%";
    $params = array_merge($params, [$sq, $sq, $sq, $sq, $sq, $sq]);
}

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

/* 2. الاستعلام المطور */
$stmt = $pdo->prepare("
    SELECT t.*, c.name AS customer_name,
           s.bill_of_lading, s.container_count,
           s.item_description, s.shipment_details,
           s.departure_date, s.expected_arrival_date, s.shipping_line,
           s.shipment_type, 
           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, t.trans_id ASC
");
$stmt->execute($params);
$rows = $stmt->fetchAll();

$customers_list = $pdo->query("SELECT customer_id, name FROM customers WHERE status='active' ORDER BY name")->fetchAll();

$total_debit  = 0;
$total_credit = 0;
$running_balance = 0;

// تجهيز رابط الطباعة مع الفلاتر الحالية
$print_url = "customer_transactions_print.php?" . http_build_query($_GET);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <title>Customer Ledger | Detailed</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; --muted: #64748b; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); margin: 0; padding: 20px; color: #334155; font-size: 13px; }
        
        .main-card { background: white; border-radius: 12px; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); border: 1px solid var(--border); overflow: hidden; }
        
        table { width: 100%; border-collapse: separate; border-spacing: 0; }
        th { background: #f8fafc; color: var(--muted); padding: 15px; font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; text-align: left; border-bottom: 2px solid var(--border); }
        td { padding: 16px; border-bottom: 1px solid var(--border); vertical-align: top; }

        .row-shipment { background-color: #f0f9ff44; } 
        tr:hover { background-color: #f1f5f9 !important; }

        .customer-badge { font-weight: 800; color: var(--accent); font-size: 13px; display: block; margin-bottom: 8px; }
        .bl-box { display: inline-block; background: var(--primary); color: white; padding: 2px 8px; border-radius: 4px; font-family: monospace; font-size: 11px; }
        
        .details-wrapper { display: flex; gap: 20px; flex-wrap: wrap; margin-top: 10px; }
        .route-flow { display: flex; align-items: center; gap: 8px; background: #fff; padding: 4px 12px; border-radius: 6px; border: 1px solid var(--border); font-size: 11px; font-weight: 600; }
        
        .date-box { font-size: 11px; color: var(--muted); line-height: 1.6; }
        .date-box b { color: var(--primary); }

        .info-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-top: 10px; width: 100%; }
        .info-card { background: #f8fafc; border: 1px solid var(--border); padding: 6px 10px; border-radius: 6px; }
        .info-card label { display: block; font-size: 9px; font-weight: 700; color: #94a3b8; text-transform: uppercase; }
        .info-card span { font-size: 11px; font-weight: 600; color: #1e293b; }

        .badge-type { background: #e0e7ff; color: #4338ca; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: bold; }

        .amt { font-family: 'Roboto Mono', monospace; font-weight: 700; text-align: right; }
        .debit-val { color: var(--danger); }
        .credit-val { color: var(--success); }
        .balance-val { background: #f8fafc; font-weight: 800; }

        .summary-footer { background: var(--primary); color: white; padding: 25px; display: flex; justify-content: flex-end; gap: 50px; }
        
        /* تنسيق حقل البحث الجمالي */
        .search-input { padding: 8px 12px; border-radius: 6px; border: 1px solid var(--border); width: 250px; 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 class="no-print" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
    <h2 style="margin:0;"><i class="fas fa-file-invoice-dollar" style="color:var(--accent)"></i> Statement of Account</h2>
    <div style="display:flex; gap:12px;">
        <a href="dashboard.php" class="btn" style="background:#64748b; color:white; text-decoration:none; padding:10px 20px; border-radius:8px; font-weight:600; display:flex; align-items:center; gap:8px;">
            <i class="fas fa-arrow-left"></i> Back
        </a>
        <a href="<?= $print_url ?>" target="_blank" style="background:var(--accent); color:white; text-decoration:none; padding:10px 20px; border-radius:8px; font-weight:600; display:flex; align-items:center; gap:8px;">
            <i class="fas fa-print"></i> Print Statement
        </a>
    </div>
</div>

<form method="GET" class="main-card no-print" style="padding:20px; margin-bottom: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 Customer</label>
        <select name="customer_id" class="select2" style="width:100%">
            <option value="">All Customers</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 style="flex:1; min-width: 200px;">
        <label style="font-size:12px; font-weight:700;">Search (B/L, Port, Line, Cargo)</label>
        <input type="text" name="search_query" value="<?= htmlspecialchars($search_query) ?>" class="search-input" style="width: 100%;" placeholder="Enter B/L or Port name...">
    </div>
    <div>
        <label style="font-size:12px; font-weight:700;">From Date</label><br>
        <input type="date" name="date_from" value="<?= $date_from ?>" style="padding:8px; border-radius:6px; border:1px solid var(--border)">
    </div>
    <div>
        <label style="font-size:12px; font-weight:700;">To Date</label><br>
        <input type="date" name="date_to" value="<?= $date_to ?>" style="padding:8px; border-radius:6px; border:1px solid var(--border)">
    </div>
    <button type="submit" style="background:var(--primary); color:white; padding:10px 25px; border:none; border-radius:6px; cursor:pointer; font-weight:600;">Search</button>
</form>

<div class="main-card">
    <table>
        <thead>
            <tr>
                <th width="110">Date / Ref</th>
                <th>Shipment & Logistics Details</th>
                <th width="120" style="text-align:right">Debit (Dr)</th>
                <th width="120" style="text-align:right">Credit (Cr)</th>
                <th width="140" style="text-align:right">Balance</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            foreach($rows as $r): 
                $is_shipment = !empty($r['shipment_id']);
                $total_debit += $r['debit'];
                $total_credit += $r['credit'];
                $running_balance += ($r['debit'] - $r['credit']);
            ?>
            <tr class="<?= $is_shipment ? 'row-shipment' : 'row-payment' ?>">
                <td>
                    <b style="color:var(--primary)"><?= $r['trans_date'] ?></b><br>
                    <small style="color:var(--muted)">TXN-<?= $r['trans_id'] ?></small>
                </td>
                <td>
                    <span class="customer-badge">
                        <i class="fas fa-user-circle"></i> <?= htmlspecialchars($r['customer_name']) ?>
                        <?php if($is_shipment && $r['shipment_type']): ?>
                            <span class="badge-type" style="margin-left:10px;"><?= $r['shipment_type'] ?></span>
                        <?php endif; ?>
                    </span>
                    
                    <?php if($is_shipment): ?>
                        <div style="margin-bottom:8px;">
                            <span class="bl-box">B/L: <?= $r['bill_of_lading'] ?: 'N/A' ?></span>
                            <strong style="margin-left:8px; color:#1e293b;"><?= htmlspecialchars($r['item_description'] ?: 'No Description') ?></strong>
                        </div>

                        <div class="details-wrapper">
                            <div class="route-flow">
                                <i class="fas fa-ship" style="color:var(--accent)"></i> <?= $r['pol_name'] ?: '---' ?>
                                <i class="fas fa-arrow-right" style="color:#cbd5e1"></i>
                                <i class="fas fa-map-marker-alt" style="color:var(--success)"></i> <?= $r['pod_name'] ?: '---' ?>
                            </div>
                            
                            <div class="date-box">
                                <b>ETD:</b> <?= $r['departure_date'] ?: '---' ?> | 
                                <b>ETA:</b> <?= $r['expected_arrival_date'] ?: '---' ?>
                            </div>
                        </div>

                        <div class="info-grid">
                            <div class="info-card"><label>Shipping Line</label><span><?= htmlspecialchars($r['shipping_line'] ?: '---') ?></span></div>
                            <div class="info-card"><label>Container Type</label><span><?= htmlspecialchars($r['container_type_name'] ?: '---') ?></span></div>
                            <div class="info-card"><label>Qty</label><span><?= $r['container_count'] ?> Unit(s)</span></div>
                            <div class="info-card" style="border-left:3px solid var(--accent)"><label>Cargo Details</label><span><?= htmlspecialchars($r['shipment_details'] ?: '---') ?></span></div>
                        </div>
                    <?php else: ?>
                        <div style="display:flex; align-items:center; gap:12px; padding:8px 0;">
                            <div style="width:32px; height:32px; background:#fff1f2; color:var(--danger); border-radius:6px; display:flex; align-items:center; justify-content:center; border:1px solid #fecdd3;">
                                <i class="fas fa-money-check-alt"></i>
                            </div>
                            <div>
                                <span style="font-weight:700; color:#991b1b;">Payment / Credit Entry</span><br>
                                <span style="color:var(--muted); font-size:12px;"><?= htmlspecialchars($r['description'] ?: 'No description provided') ?></span>
                            </div>
                        </div>
                    <?php endif; ?>
                </td>
                <td class="amt debit-val"><?= $r['debit'] > 0 ? number_format($r['debit'], 2) : '-' ?></td>
                <td class="amt credit-val"><?= $r['credit'] > 0 ? number_format($r['credit'], 2) : '-' ?></td>
                <td class="amt balance-val"><?= number_format($running_balance, 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="summary-footer">
        <div style="text-align:right">
            <div style="font-size:10px; color:#cbd5e1; text-transform:uppercase">Total Charges</div>
            <div style="font-size:20px; font-weight:800; color:#f87171"><?= number_format($total_debit, 2) ?></div>
        </div>
        <div style="text-align:right">
            <div style="font-size:10px; color:#cbd5e1; text-transform:uppercase">Total Payments</div>
            <div style="font-size:20px; font-weight:800; color:#34d399"><?= number_format($total_credit, 2) ?></div>
        </div>
        <div style="text-align:right; border-left: 1px solid #475569; padding-left: 40px;">
            <div style="font-size:10px; color:#cbd5e1; text-transform:uppercase">Net Outstanding Balance</div>
            <div style="font-size:20px; 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>
    $(document).ready(function() {
        $('.select2').select2({
            placeholder: "Search for a customer..."
        });
    });
</script>
</body>
</html>