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

/* ==========================================================================
   1. محرك البحث والفلترة المتقدم (مقتبس من صفحة الشحنات)
   ========================================================================== */
$f_search   = trim($_GET['f_search'] ?? '');
$f_item     = trim($_GET['f_item'] ?? '');
$f_date     = trim($_GET['f_date'] ?? '');
$f_status   = trim($_GET['f_status'] ?? '');
$f_agent    = trim($_GET['f_agent'] ?? ''); 
$f_customer = trim($_GET['f_customer'] ?? ''); 
$f_ct_type  = trim($_GET['f_ct_type'] ?? ''); 

// بناء رابط الطباعة مع كافة الفلاتر
$query_params = $_GET; 
$print_url = "price_offer_print.php?" . http_build_query($query_params);

$conditions = ["1=1"];
$params = [];

if ($f_search !== '') { 
    $conditions[] = "(s.shipping_line LIKE ? OR s.offer_id LIKE ?)"; 
    $params[] = "%$f_search%"; $params[] = "%$f_search%"; 
}
if ($f_item !== '') { $conditions[] = "s.item_description LIKE ?"; $params[] = "%$f_item%"; }
if ($f_date !== '') { $conditions[] = "s.offer_date = ?"; $params[] = $f_date; }
if ($f_agent !== '') { $conditions[] = "s.agent_id = ?"; $params[] = $f_agent; }
if ($f_customer !== '') { $conditions[] = "s.customer_id = ?"; $params[] = $f_customer; }
if ($f_ct_type !== '') { $conditions[] = "s.container_type_id = ?"; $params[] = $f_ct_type; }

if ($f_status === 'Active') {
    $conditions[] = "(s.status = 'Active' OR s.status = 'approved')";
} elseif ($f_status === 'Inactive') {
    $conditions[] = "(s.status = 'Inactive' OR s.status = 'rejected')";
}

$where = "WHERE " . implode(" AND ", $conditions);

// جلب بيانات القوائم المنسدلة للفلترة
$all_agents = $pdo->query("SELECT agent_id, name FROM agents ORDER BY name ASC")->fetchAll();
$all_customers = $pdo->query("SELECT customer_id, name FROM customers ORDER BY name ASC")->fetchAll();
$container_types = $pdo->query("SELECT container_id, container_type FROM container_types ORDER BY container_type ASC")->fetchAll();

/* ==========================================================================
   2. الاستعلام الشامل مع الـ Joins
   ========================================================================== */
$stmt = $pdo->prepare("
    SELECT s.*, 
           ag.name AS agent_name, 
           c.name AS customer_name,
           ct.container_type AS container_type_name
    FROM price_offers s
    LEFT JOIN agents ag ON s.agent_id = ag.agent_id
    LEFT JOIN customers c ON s.customer_id = c.customer_id
    LEFT JOIN container_types ct ON s.container_type_id = ct.container_id
    $where
    ORDER BY s.offer_id DESC
");
$stmt->execute($params);
$offers = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Price Offers Management</title>
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/css/select2.min.css" rel="stylesheet" />
    <style>
        :root{
            --bg:#f8fafc; --card:#ffffff; --border:#e2e8f0; --text:#1e293b;
            --muted:#64748b; --primary:#2563eb; --success:#10b981;
            --danger:#ef4444; --warning:#f59e0b; --shadow:0 4px 6px -1px rgba(0,0,0,0.1);
        }
        body{ margin:0; font-family:'Segoe UI', sans-serif; background:var(--bg); color:var(--text); font-size: 13px; }
        .container{padding:20px}
        .page-header{ display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; }
        .btn{ padding:8px 16px; border-radius:8px; font-size:12px; font-weight:600; text-decoration:none; display:inline-flex; align-items:center; gap:8px; border:none; cursor:pointer; color:#fff; }
        .btn-primary{background:var(--primary)}
        .btn-success{background:var(--success)}
        .btn-gray{background:#475569}
        .btn-print{background:#0891b2}

        .filter-card { background: var(--card); padding: 20px; border-radius: 12px; border: 1px solid var(--border); margin-bottom: 20px; box-shadow: var(--shadow); }
        .filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; }
        .filter-item label { font-size: 11px; font-weight: bold; color: var(--muted); margin-bottom: 5px; display: block; text-transform: uppercase; }
        
        .select2-container--default .select2-selection--single { height: 38px !important; border: 1px solid var(--border) !important; border-radius: 6px !important; }
        .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 36px !important; }

        .card{ background:var(--card); border-radius:12px; box-shadow:var(--shadow); border:1px solid var(--border); overflow-x:auto; }
        table{width:100%; border-collapse:collapse; min-width: 1100px;}
        th{ background:#f1f5f9; padding:12px; font-size:11px; text-align: left; color:var(--muted); border-bottom: 2px solid var(--border); text-transform: uppercase; }
        td{ padding:15px 12px; border-bottom: 1px solid var(--border); vertical-align: top; }

        .info-label { font-size: 10px; color: var(--muted); font-weight: bold; text-transform: uppercase; display: block; margin-bottom: 2px; }
        .info-value { display: block; margin-bottom: 8px; }
        .money { font-weight: bold; color: #000; }
        .grand-total { color: var(--success); font-size: 14px; }
        
        .badge{ padding:3px 8px; border-radius:6px; font-size:10px; font-weight:700; text-transform: uppercase; }
        .badge-active{background:#dcfce7; color:#065f46}
        .badge-inactive{background:#fee2e2; color:#991b1b}
        
        .action-btns { display: flex; gap: 5px; }
        .act-btn { width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 6px; color: #fff; text-decoration: none; font-size: 12px; transition: 0.2s; }
        .act-btn:hover { transform: translateY(-2px); opacity: 0.9; }
    </style>
</head>
<body>

<div class="container">
    <div class="page-header">
        <h2 style="margin:0">💰 Price Offers Management</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?= $print_url ?>" target="_blank" class="btn btn-print"><i class="fas fa-print"></i> Print Version</a>
            <a href="dashboard.php" class="btn btn-gray"><i class="fas fa-arrow-left"></i> Back</a>
            <a href="price_offer_add.php" class="btn btn-success"><i class="fas fa-plus"></i> New Offer</a>
        </div>
    </div>

    <div class="filter-card">
        <form method="GET">
            <div class="filter-grid">
                <div class="filter-item">
                    <label>Offer ID / Line</label>
                    <input type="text" name="f_search" value="<?= htmlspecialchars($f_search) ?>" placeholder="Search..." style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px;">
                </div>
                <div class="filter-item">
                    <label>Agent</label>
                    <select name="f_agent" class="select-search">
                        <option value="">All Agents</option>
                        <?php foreach($all_agents as $ag): ?>
                            <option value="<?= $ag['agent_id'] ?>" <?= $f_agent == $ag['agent_id'] ? 'selected' : '' ?>><?= htmlspecialchars($ag['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-item">
                    <label>Customer</label>
                    <select name="f_customer" class="select-search">
                        <option value="">All Customers</option>
                        <?php foreach($all_customers as $cust): ?>
                            <option value="<?= $cust['customer_id'] ?>" <?= $f_customer == $cust['customer_id'] ? 'selected' : '' ?>><?= htmlspecialchars($cust['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-item">
                    <label>Container Type</label>
                    <select name="f_ct_type" class="select-search">
                        <option value="">All Types</option>
                        <?php foreach($container_types as $ct): ?>
                            <option value="<?= $ct['container_id'] ?>" <?= $f_ct_type == $ct['container_id'] ? 'selected' : '' ?>><?= htmlspecialchars($ct['container_type']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-item">
                    <label>Offer Date</label>
                    <input type="date" name="f_date" value="<?= htmlspecialchars($f_date) ?>" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px;">
                </div>
                <div class="filter-item">
                    <label>Status</label>
                    <select name="f_status" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px;">
                        <option value="">All Status</option>
                        <option value="Active" <?= $f_status == 'Active' ? 'selected' : '' ?>>Active/Approved</option>
                        <option value="Inactive" <?= $f_status == 'Inactive' ? 'selected' : '' ?>>Inactive/Rejected</option>
                    </select>
                </div>
            </div>
            <button type="submit" class="btn btn-primary" style="margin-top:15px;"><i class="fas fa-filter"></i> Apply Filters</button>
        </form>
    </div>

    <div class="card">
        <table>
            <thead>
                <tr>
                    <th>Ref / Customer / Agent</th>
                    <th>Shipping Line & Type</th>
                    <th>Cargo & Volume</th>
                    <th>Financials</th>
                    <th>Status & Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($offers as $o): 
                    $st = strtolower($o['status'] ?? '');
                    $is_active = ($st === 'active' || $st === 'approved');
                ?>
                <tr>
                    <td>
                        <span class="info-label">Offer ID</span>
                        <strong class="info-value">#<?= $o['offer_id'] ?></strong>
                        <span class="info-label">Customer</span>
                        <span class="info-value" style="color:var(--success); font-weight:600;"><?= htmlspecialchars($o['customer_name'] ?: 'N/A') ?></span>
                        <span class="info-label">Agent</span>
                        <span class="info-value" style="color:var(--primary); font-weight:600;"><?= htmlspecialchars($o['agent_name'] ?: 'N/A') ?></span>
                    </td>
                    <td>
                        <span class="info-label">Shipping Line</span>
                        <div class="info-value"><i class="fas fa-ship"></i> <?= htmlspecialchars($o['shipping_line'] ?: '---') ?></div>
                        <span class="info-label">Service Type</span>
                        <div class="info-value"><?= htmlspecialchars($o['order_type']) ?></div>
                    </td>
                    <td>
                        <span class="info-label">Description</span>
                        <div class="info-value" style="max-width:200px;"><?= htmlspecialchars($o['item_description']) ?></div>
                        <span class="info-label">Volume</span>
                        <div class="info-value">
                            <span class="badge" style="background:#e0e7ff; color:#3730a3"><?= htmlspecialchars($o['container_type_name'] ?: 'Unit') ?></span>
                            <span class="badge" style="background:#fef3c7; color:#92400e">X<?= $o['container_count'] ?></span>
                        </div>
                    </td>
                    <td>
                        <span class="info-label">Price / Unit</span>
                        <span class="info-value money"><?= number_format($o['price_per_container'], 2) ?></span>
                        <span class="info-label">Grand Total</span>
                        <span class="info-value money grand-total"><?= number_format($o['grand_total'], 2) ?></span>
                    </td>
                    <td>
                        <span class="badge <?= $is_active ? 'badge-active' : 'badge-inactive' ?>"><?= $o['status'] ?: 'Active' ?></span>
                        <span class="info-label" style="margin-top:8px;">Offer Date</span>
                        <div class="info-value" style="font-family: monospace;"><?= $o['offer_date'] ?></div>
                    </td>
                    <td>
                        <div class="action-btns">
                            <a href="price_offer_view.php?id=<?= $o['offer_id'] ?>" class="act-btn" style="background:var(--primary)" title="View"><i class="fas fa-eye"></i></a>
                            <a href="price_offer_edit.php?id=<?= $o['offer_id'] ?>" class="act-btn" style="background:var(--warning)" title="Edit"><i class="fas fa-edit"></i></a>
                            <a href="price_offer_delete.php?id=<?= $o['offer_id'] ?>" class="act-btn" style="background:var(--danger)" title="Delete" onclick="return confirm('Are you sure?')"><i class="fas fa-trash"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if(empty($offers)): ?>
                    <tr><td colspan="6" style="text-align:center; padding:30px; color:var(--muted);">No offers found matching your criteria.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </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() {
    $('.select-search').select2({
        placeholder: "Search and Select...",
        allowClear: true,
        width: '100%'
    });
});
</script>
</body>
</html>