<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

function e($v): string {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

function fmt_date($d): string {
    if (empty($d) || $d === '0000-00-00') {
        return '-';
    }
    $ts = strtotime($d);
    return $ts ? date('d M Y', $ts) : '-';
}

function find_country_id_for_user(mysqli $conn, string $user_country_value): int {
    $user_country_value = trim($user_country_value);
    if ($user_country_value === '') {
        return 0;
    }

    $lc = mb_strtolower($user_country_value);
    $res = $conn->query("SELECT * FROM countries");
    if (!$res) {
        return 0;
    }

    while ($r = $res->fetch_assoc()) {
        foreach ($r as $val) {
            if ($val === null) {
                continue;
            }
            if (mb_strtolower((string)$val) === $lc) {
                return (int)$r['id'];
            }
        }

        if (isset($r['country_name'])) {
            $cn = mb_strtolower((string)$r['country_name']);
            if ($cn === $lc) {
                return (int)$r['id'];
            }
            if (mb_stripos($cn, $user_country_value) !== false) {
                return (int)$r['id'];
            }
            if (mb_stripos($user_country_value, $cn) !== false) {
                return (int)$r['id'];
            }
        }
    }

    return 0;
}

function build_where_clause(mysqli $conn, string $session_role, string $session_country_code, string $q, array &$params, string &$types): string
{
    $where = ["p.status = 'approved'"];

    if ($session_role === 'sales_manager') {
        $country_id = 0;
        if ($session_country_code !== '') {
            $country_id = find_country_id_for_user($conn, $session_country_code);
        }

        if ($country_id > 0) {
            $where[] = "p.country_id = ?";
            $params[] = $country_id;
            $types .= 'i';
        } else {
            $where[] = "1=0";
        }
    }

    if ($q !== '') {
        $where[] = "(
            p.product_name LIKE ?
            OR p.generic_name LIKE ?
            OR p.brand_name LIKE ?
            OR p.dossier_number LIKE ?
            OR p.registration_number LIKE ?
        )";
        $like = "%{$q}%";
        array_push($params, $like, $like, $like, $like, $like);
        $types .= 'sssss';
    }

    return 'WHERE ' . implode(' AND ', $where);
}

function bind_params(mysqli_stmt $stmt, string $types, array $params): void
{
    if ($types === '' || empty($params)) {
        return;
    }

    $bind = [];
    $bind[] = $types;
    foreach ($params as $k => $v) {
        $bind[] = &$params[$k];
    }
    call_user_func_array([$stmt, 'bind_param'], $bind);
}

function render_product_row(array $p, array $valid_columns, int $sr, string $csrf): string
{
    ob_start();
    ?>
    <tr>
        <td data-label="No."><?= $sr ?></td>

       <?php foreach ($valid_columns as $col): ?>
    <td data-label="<?= e($allowed_columns[$col]) ?>">
        <?= e($p[$col] ?? '-') ?>
    </td>
<?php endforeach; ?>

        <td data-label="Country">
    <?= e($p['country_name'] ?? '-') ?>
</td>

<td data-label="Date">
    <?= fmt_date($p['created_at'] ?? '') ?>
</td>

<td data-label="Registration Date">
    <?= e($p['purchase_name'] ?? '-') ?>
</td>

<td data-label="File">
    <?php if (!empty($p['file_path'])): ?>
        <a class="icon-btn" target="_blank" href="../<?= e($p['file_path']) ?>" title="Open File">
            <i class="fa fa-file"></i>
        </a>
    <?php else: ?>
        <span class="muted-text">-</span>
    <?php endif; ?>
</td>

<td data-label="Action">
    <div class="action-group">
        <button type="button"
                class="icon-btn"
                title="Preview"
                onclick="previewProduct(
                    `<?= addslashes('<b>Product:</b> ' . e($p['product_name'] ?? '-') . '<br>'
                    . '<b>Brand:</b> ' . e($p['brand_name'] ?? '-') . '<br>'
                    . '<b>Generic:</b> ' . e($p['generic_name'] ?? '-') . '<br>'
                    . '<b>Country:</b> ' . e($p['country_name'] ?? '-') . '<br>'
                    . '<b>Date:</b> ' . fmt_date($p['created_at'] ?? '') . '<br>'
                    . '<b>Registration:</b> ' . fmt_date($p['registration_date'] ?? '')) ?>`
                )">
            <i class="fa fa-eye"></i>
        </button>

        <form method="post" onsubmit="return confirm('Delete this product?');" style="display:inline;">
            <input type="hidden" name="csrf_token" value="<?= e($csrf) ?>">
            <input type="hidden" name="delete_id" value="<?= (int)($p['id'] ?? 0) ?>">
            <button type="submit" class="icon-btn danger" title="Delete">
                <i class="fa fa-trash"></i>
            </button>
        </form>
    </div>
</td>
    </tr>
    <?php
    return ob_get_clean();
}

$errors = [];
$messages = [];

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_token'];

$session_user_id = (int)($_SESSION['user_id'] ?? 0);
$session_role = '';
$session_country_code = '';

if ($session_user_id > 0) {
    $uStmt = $conn->prepare("SELECT role, country FROM users WHERE id = ? LIMIT 1");
    if ($uStmt) {
        $uStmt->bind_param("i", $session_user_id);
        $uStmt->execute();
        $uRes = $uStmt->get_result();
        if ($uRes && $uRes->num_rows === 1) {
            $uRow = $uRes->fetch_assoc();
            $session_role = strtolower(trim($uRow['role'] ?? ''));
            $session_country_code = trim((string)($uRow['country'] ?? ''));
        }
        $uStmt->close();
    }
}

/* DELETE PRODUCT */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $errors[] = 'Invalid request.';
    } else {
        $del_id = (int)$_POST['delete_id'];

        $stmt = $conn->prepare("SELECT file_path FROM products WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param("i", $del_id);
            $stmt->execute();
            $res = $stmt->get_result();
            $row = $res ? $res->fetch_assoc() : null;
            $stmt->close();

            $stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
            $stmt->bind_param("i", $del_id);

            if ($stmt->execute()) {
                if (!empty($row['file_path'])) {
                    $file = __DIR__ . '/../' . $row['file_path'];
                    if (file_exists($file)) {
                        unlink($file);
                    }
                }
                $messages[] = 'Product deleted successfully.';
            } else {
                $errors[] = 'Delete failed.';
            }
            $stmt->close();
        }
    }
}

/* AVAILABLE COLUMNS */
 $allowed_columns = [
    
        /* Commercial Product Info */
        'product_name' => 'Product Name',
        'generic_name' => 'Generic Name',
        'brand_name' => 'Brand Name',
        'standards' => 'Standards',
        'strength' => 'Strength',
        'volume' => 'Volume',
        'dosage_form' => 'Dosage Form',
        'indication' => 'Indication',
        'primary_packing' => 'Primary Packing',
        'secondary_packing' => 'Secondary Packing',
        'shelf_life' => 'Shelf Life',
        'manufactured_by' => 'Manufactured By',
        'marketed_by' => 'Marketed By',
        'distributed_by' => 'Distributed By',
    
        /* Samples Details */
        'samples_batch_no' => 'Samples Batch No',
        'samples_manufacturing_date' => 'Samples Manufacturing Date',
        'samples_expiry_date' => 'Samples Expiry Date',
        'samples_submitted_on' => 'Samples Submitted On',
        'samples_tracking_no' => 'Samples Tracking No',
        'samples_qty' => 'Samples Qty',
        'samples_sent_to' => 'Samples Sent To',
        'samples_destination_address' => 'Samples Destination Address',
    
        /* WS Details */
        'ws_batch_no' => 'WS Batch No',
        'ws_manufacturing_date' => 'WS Manufacturing Date',
        'ws_expiry_date' => 'WS Expiry Date',
        'ws_submitted_on' => 'WS Submitted On',
        'ws_tracking_no' => 'WS Tracking No',
        'ws_qty' => 'WS Qty',
        'ws_sent_to' => 'WS Sent To',
        'ws_destination_address' => 'WS Destination Address',
    
        /* Dossier Details */
        'dossier_number' => 'Dossier Number',
        'submitted_to' => 'Submitted To',
        'dossier_sent_on' => 'Dossier Sent On',
        'query_received_on' => 'Query Received On',
        'query_submitted_on' => 'Query Submitted On',
        'dossier_submitted_in_moh_on' => 'Dossier Submitted In MOH On',
        'moh_comments_received_on' => 'MOH Comments Received On',
        'moh_comments' => 'MOH Comments',
        'moh_comments_submitted_on' => 'MOH Comments Submitted On',
    
        /* Registration */
        'registration_number' => 'Registration Number',
        'registration_details' => 'Registration Details',
        'purchase_name' => 'Purchase Name',
        'registration_exp_date' => 'Registration Expiry Date',
        'renewal_process_start' => 'Renewal Process Start',
        'variation_submitted' => 'Variation Submitted',
        'variation_approval_date' => 'Variation Approval Date',
    
        /* Pricing */
        'qty' => 'Balance Quantity',
        'units_per_packet' => 'Units Per Packet',
        'price_per_packet' => 'Price Per Packet',
        'hsn_no' => 'HSN No.',   // ✅ ADD THIS
    ];
    

$selected_columns = $_GET['columns'] ?? ['product_name', 'brand_name', 'dossier_number', 'registration_number'];
$valid_columns = [];
foreach ($selected_columns as $col) {
    if (isset($allowed_columns[$col])) {
        $valid_columns[] = $col;
    }
}
if (!$valid_columns) {
    $valid_columns = ['product_name'];
}

$q = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

/* WHERE CLAUSE */
$params = [];
$types = '';
$where_sql = build_where_clause($conn, $session_role, $session_country_code, $q, $params, $types);

/* AJAX SEARCH */
if (isset($_GET['ajax'])) {
    $sql = "
        SELECT p.*, c.country_name
        FROM products p
        LEFT JOIN countries c ON c.id = p.country_id
        $where_sql
        ORDER BY p.created_at DESC, p.id DESC
        LIMIT 50
    ";

    $stmt = $conn->prepare($sql);
    if ($stmt && $types !== '') {
        bind_params($stmt, $types, $params);
    }
    if ($stmt) {
        $stmt->execute();
        $res = $stmt->get_result();

        $i = 1;
        while ($p = $res->fetch_assoc()) {
            echo render_product_row($p, $valid_columns, $i++, $csrf);
        }
        $stmt->close();
    }
    exit;
}

/* TOTAL COUNT */
$sql_count = "SELECT COUNT(*) AS total FROM products p LEFT JOIN countries c ON c.id = p.country_id $where_sql";
$stmt = $conn->prepare($sql_count);
if ($stmt && $types !== '') {
    bind_params($stmt, $types, $params);
}
$total = 0;
if ($stmt) {
    $stmt->execute();
    $total = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    $stmt->close();
}

/* PRODUCT LIST */
$sql = "
    SELECT p.*, c.country_name
    FROM products p
    LEFT JOIN countries c ON c.id = p.country_id
    $where_sql
    ORDER BY p.created_at DESC, p.id DESC
    LIMIT ? OFFSET ?
";

$stmt = $conn->prepare($sql);
$params2 = $params;
$params2[] = $per_page;
$params2[] = $offset;
$types2 = $types . 'ii';

if ($stmt) {
    if ($types2 === 'ii') {
        $stmt->bind_param("ii", $per_page, $offset);
    } else {
        bind_params($stmt, $types2, $params2);
    }
    $stmt->execute();
    $result = $stmt->get_result();

    $products = [];
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
    $stmt->close();
} else {
    $products = [];
}

$total_pages = $per_page > 0 ? (int)ceil($total / $per_page) : 1;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>All Commercial Products</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
    :root{
        --bg:#eef3f9;
        --card:#ffffff;
        --text:#0f172a;
        --muted:#64748b;
        --border:#dfe7f1;
        --shadow:0 16px 35px rgba(15,23,42,.08);
        --shadow-soft:0 10px 24px rgba(15,23,42,.06);
        --radius:18px;
        --primary:#374155;
    }

    *{ box-sizing:border-box; }

    body{
        margin:0;
        font-family:Inter, Arial, Helvetica, sans-serif;
        background:var(--bg);
        color:var(--text);
    }

    a{
        text-decoration:none;
        color:inherit;
    }

    .container{
        margin-left:260px;
        margin-top:0;
        padding:0 16px 16px;
    }

    .page-title{
        padding:25px 0 12px;
        margin:0;
    }

    .page-title h1{
        margin:0;
        font-size:22px;
        color:#0b1b3a;
        font-weight:700;
        letter-spacing:.2px;
        display:flex;
        align-items:center;
        gap:12px;
        line-height:1.2;
    }

    .page-title h1 i{
        background:#eef2f7;
        color:#374155;
        width:36px;
        height:36px;
        display:flex;
        align-items:center;
        justify-content:center;
        border-radius:14px;
        font-size:14px;
        flex:0 0 auto;
    }

    .page-title p{
        margin:6px 0 0;
        color:var(--muted);
        font-size:13px;
        line-height:1.5;
    }

    .card{
        background:var(--card);
        border:1px solid var(--border);
        border-radius:18px;
        box-shadow:var(--shadow);
        padding:12px;
    }

    .top-bar{
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:12px;
        flex-wrap:wrap;
        margin-bottom:12px;
    }

    .top-bar h2{
        margin:0;
        font-weight:800;
        font-size:18px;
        color:#0f172a;
    }

    .export-btn{
        background:#16a34a;
        color:#fff;
        padding:10px 16px;
        border-radius:12px;
        font-size:13px;
        text-decoration:none;
        display:inline-flex;
        align-items:center;
        gap:8px;
        font-weight:700;
        border:none;
    }

    .export-btn:hover{
        background:#15803d;
    }

    .alert{
        margin-bottom:12px;
        padding:10px 12px;
        border-radius:12px;
        font-size:13px;
        font-weight:600;
    }

    .alert.success{
        background:#ecfdf5;
        color:#166534;
        border:1px solid #bbf7d0;
    }

    .alert.error{
        background:#fef2f2;
        color:#991b1b;
        border:1px solid #fecaca;
    }

   .controls{
    display:flex;
    gap:12px;
    align-items:center;   /* FIX ALIGNMENT */
    flex-wrap:wrap;
    margin-top:0;         /* REMOVE TOP SPACE */
    margin-bottom:10px;
}
.controls .export-btn{
    margin-left:auto;
    background-color: #374155;
}


    .column-box{
        position:relative;
        display:inline-block;
    }

    .btn{
        background:#374155;
        color:#fff;
        padding:10px 14px;
        border-radius:12px;
        border:none;
        cursor:pointer;
        font-size:13px;
        text-decoration:none;
        display:inline-flex;
        align-items:center;
        gap:8px;
        font-weight:700;
    }

    .btn:hover{
        background:#273142;
    }

    .btn-light{
        background:#fff;
        color:#0f172a;
        border:1px solid #d1d5db;
    }

    .btn-light:hover{
        background:#f8fafc;
    }

    .btn-danger{
        background:#ef4444;
    }

    .btn-danger:hover{
        background:#dc2626;
    }

    .search-box{
        display:flex;
        align-items:center;
        gap:10px;
        flex:1;
        min-width:160px;
        max-width:520px;
        background:#fff;
        border:1px solid #d8e0ea;
        border-radius:14px;
        padding:5px 12px;
        box-shadow:0 1px 2px rgba(0,0,0,.03);
    }

    .search-box i{
        font-size:15px;
        color:#111827;
    }

    .search-box input{
        width:100%;
        border:none;
        outline:none;
        font-size:13px;
        background:transparent;
        color:var(--text);
    }

    #columnDropdown{
        display:none;
        position:absolute;
        top:44px;
        left:0;
        background:#fff;
        border:1px solid #d8e0ea;
        border-radius:14px;
        padding:14px;
        box-shadow:0 14px 32px rgba(15,23,42,.12);
        width:340px;
        z-index:100;
    }

    .column-grid{
        display:grid;
        grid-template-columns:repeat(2, minmax(0, 1fr));
        gap:8px;
        max-height:220px;
        overflow:auto;
    }

    .column-grid label{
        display:flex;
        gap:8px;
        align-items:flex-start;
        font-size:13px;
        color:#0f172a;
    }

    .table-wrap{
        width:100%;
        overflow:auto;
        border:1px solid #e5e7eb;
        border-radius:16px;
        background:#fff;
    }

    table{
        width:100%;
        border-collapse:separate;
        border-spacing:0;
        min-width:1220px;
    }

    thead th{
        position:sticky;
        top:0;
        z-index:2;
        background:#374155;
        color:#fff;
        padding:12px 12px;
        font-size:12px;
        font-weight:800;
        text-transform:uppercase;
        letter-spacing:.04em;
        text-align:left;
        white-space:nowrap;
    }

    tbody td{
        padding:12px;
        border-bottom:1px solid #eef2f7;
        font-size:13px;
        color:#111827;
        vertical-align:middle;
        white-space:nowrap;
        background:#fff;
    }

    tbody tr:hover td{
        background:#f8fbff;
    }

    tbody tr:last-child td{
        border-bottom:none;
    }

    td:first-child,
    th:first-child{
        width:70px;
    }

    .muted-text{
        color:var(--muted);
    }

    .icon-btn{
        width:34px;
        height:34px;
        border-radius:10px;
        background:#e2e8f0;
        color:#111827;
        border:none;
        display:inline-flex;
        align-items:center;
        justify-content:center;
        cursor:pointer;
        font-size:13px;
    }

    .icon-btn:hover{
        background:#cbd5e1;
    }

    .icon-btn.danger{
        background:#fee2e2;
        color:#b91c1c;
    }

    .icon-btn.danger:hover{
        background:#fecaca;
    }

    .action-group{
        display:flex;
        gap:8px;
        align-items:center;
    }

    .pagination{
        display:flex;
        gap:8px;
        margin-top:16px;
        flex-wrap:wrap;
    }

    .pagination a{
        padding:8px 12px;
        border-radius:10px;
        border:1px solid #d1d5db;
        text-decoration:none;
        background:#fff;
        font-size:13px;
        color:#0f172a;
    }

    .pagination a.active{
        background:#374155;
        color:#fff;
        border-color:#374155;
    }

    .pagination a:hover{
        background:#f8fafc;
    }

    .modal-overlay{
        display:none;
        position:fixed;
        inset:0;
        background:rgba(0,0,0,.6);
        align-items:center;
        justify-content:center;
        z-index:9999;
        padding:16px;
    }

    .modal{
        background:#fff;
        border-radius:16px;
        max-width:640px;
        width:100%;
        padding:20px;
        box-shadow:0 20px 50px rgba(0,0,0,.25);
    }

    .modal h3{
        margin:0 0 12px;
        font-size:18px;
        color:#0f172a;
    }

    .modal-content{
        color:#111827;
        font-size:14px;
        line-height:1.7;
    }

    .modal-actions{
        margin-top:16px;
        display:flex;
        justify-content:flex-end;
    }

    @media (max-width:900px){
        .container{
            margin-left:0;
            padding:0 12px 12px;
        }

        .search-box{
            max-width:100%;
        }

        .controls{
            flex-direction:column;
            align-items:stretch;
        }

        .btn,
        .export-btn{
            justify-content:center;
            width:100%;
        }

        .table-wrap{
            border-radius:14px;
        }
    }
    /* ================= ULTRA MOBILE RESPONSIVE ================= */
@media (max-width:768px){

    /* MAIN CONTAINER */
    .container{
        margin-left:0;
        padding:0 10px 12px;
    }

    /* TITLE */
    .page-title{
        padding:18px 0 10px;
    }

    .page-title h1{
        font-size:18px;
    }

    .page-title p{
        font-size:12px;
    }

    /* CONTROLS STACK */
    .controls{
        flex-direction:column;
        align-items:stretch;
        gap:10px;
    }

    .search-box{
        width:100%;
        max-width:100%;
    }

    .btn,
    .export-btn{
        width:100%;
        justify-content:center;
    }

    /* ðŸ”¥ TABLE â†’ CARD VIEW */
    .table-wrap{
        overflow:visible;
        border:none;
    }

    table{
        min-width:100%;
    }

    table thead{
        display:none;
    }

    table,
    tbody,
    tr,
    td{
        display:block;
        width:100%;
    }

    /* CARD STYLE */
    tbody tr{
        background:#fff;
        border:1px solid #e5e7eb;
        border-radius:16px;
        padding:14px;
        margin-bottom:12px;
        box-shadow:0 6px 14px rgba(0,0,0,0.05);
    }

    /* CELL STYLE */
    tbody td{
        display:flex;
        justify-content:space-between;
        align-items:center;
        padding:6px 0;
        font-size:13px;
        border-bottom:1px dashed #eee;
        white-space:normal;
    }

    tbody td:last-child{
        border-bottom:none;
    }

    /* LABELS */
    tbody td::before{
        content:attr(data-label);
        font-weight:600;
        font-size:11px;
        color:#64748b;
    }

    /* SR CENTER */
    tbody td:first-child{
        justify-content:center;
        font-weight:800;
        border-bottom:1px solid #ddd;
        margin-bottom:6px;
    }

    /* ACTION BUTTONS */
    .action-group{
        justify-content:flex-end;
    }

    /* PAGINATION */
    .pagination{
        justify-content:center;
    }

    .pagination a{
        flex:1;
        text-align:center;
    }
}
</style>
</head>
<body>

<?php include '../header.php'; ?>
<?php include 'salesmanagersidebar.php'; ?>

<div class="container">
    <div class="page-title">
        <h1>
            <i class="fa-solid fa-boxes-stacked"></i>
            All Commercial Products
        </h1>
        <p>Manage and view approved products with country, date, and registration details.</p>
    </div>

    <div class="card">
     

        <?php if (!empty($messages)): ?>
            <?php foreach ($messages as $m): ?>
                <div class="alert success"><?= e($m) ?></div>
            <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
            <?php foreach ($errors as $er): ?>
                <div class="alert error"><?= e($er) ?></div>
            <?php endforeach; ?>
        <?php endif; ?>

<div class="controls">

    <div class="column-box">

    <button type="button" class="btn btn-light" onclick="toggleColumns()">
        <i class="fa fa-table"></i> Columns
    </button>

    <div id="columnDropdown">

        <form method="get">

            <div class="column-grid">

                <?php foreach($allowed_columns as $key => $label): ?>

                    <label>

                        <input type="checkbox"
                               name="columns[]"
                               value="<?= e($key) ?>"
                               <?= in_array($key, $valid_columns) ? 'checked' : '' ?>>

                        <?= e($label) ?>

                    </label>

                <?php endforeach; ?>

            </div>

            <div style="margin-top:12px;display:flex;gap:8px;">

                <button type="submit" class="btn">
                    Apply
                </button>

                <a href="?" class="btn btn-light">
                    Reset
                </a>

            </div>

        </form>

    </div>

</div>

    <form class="search-box" method="get">
        <?php foreach ($valid_columns as $vc): ?>
            <input type="hidden" name="columns[]" value="<?= e($vc) ?>">
        <?php endforeach; ?>

        <i class="fa fa-search"></i>
        <input type="search" id="searchInput" name="q" placeholder="Search product..." value="<?= e($q) ?>">

        <button class="btn" type="submit">Search</button>
    </form>

    <!-- âœ… ADD THIS -->
    <a href="export_products_excel.php" class="export-btn">
        <i class="fa fa-file-excel"></i> Export
    </a>

</div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>No.</th>
                        <?php foreach ($valid_columns as $col): ?>
                            <th><?= e($allowed_columns[$col]) ?></th>
                        <?php endforeach; ?>
                        <th>Country</th>
                        <th>Date</th>
                        <th>Purchase Name</th>
                        <th>File</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="productTable">
                    <?php if (empty($products)): ?>
                        <tr>
                            <td colspan="<?= 6 + count($valid_columns) ?>" style="text-align:center;padding:22px;color:#64748b;">
                                No products found.
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php $i = $offset + 1; foreach ($products as $p): ?>
                            <?= render_product_row($p, $valid_columns, $i++, $csrf) ?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="pagination">
            <?php
            for ($i = 1; $i <= $total_pages; $i++):
                $qs = [];
                if ($q !== '') {
                    $qs[] = 'q=' . urlencode($q);
                }
                foreach ($valid_columns as $vc) {
                    $qs[] = 'columns[]=' . urlencode($vc);
                }
                $qs[] = 'page=' . $i;
                $link = '?' . implode('&', $qs);
            ?>
                <a href="<?= e($link) ?>" class="<?= $i === $page ? 'active' : '' ?>"><?= $i ?></a>
            <?php endfor; ?>
        </div>
    </div>
</div>

<div id="previewModal" class="modal-overlay">
    <div class="modal">
        <h3>Product Details</h3>
        <div id="previewContent" class="modal-content"></div>
        <div class="modal-actions">
            <button type="button" class="btn" onclick="closePreview()">Close</button>
        </div>
    </div>
</div>

<script>
function toggleColumns() {
    const box = document.getElementById('columnDropdown');
    box.style.display = box.style.display === 'block' ? 'none' : 'block';
}

document.addEventListener('click', function (e) {
    const box = document.getElementById('columnDropdown');
    const button = e.target.closest('.column-box');
    if (!button) {
        box.style.display = 'none';
    }
});

function previewProduct(data) {
    document.getElementById('previewContent').innerHTML = data;
    document.getElementById('previewModal').style.display = 'flex';
}

function closePreview() {
    document.getElementById('previewModal').style.display = 'none';
}

document.getElementById('previewModal').addEventListener('click', function (e) {
    if (e.target === this) {
        closePreview();
    }
});

let timer;
const searchInput = document.getElementById('searchInput');

if (searchInput) {
    searchInput.addEventListener('keyup', function () {
        clearTimeout(timer);
        const query = this.value;

        timer = setTimeout(() => {
            const params = new URLSearchParams(window.location.search);
            params.set('ajax', '1');
            params.set('q', query);

            fetch('?' + params.toString())
                .then(res => res.text())
                .then(data => {
                    document.getElementById('productTable').innerHTML = data;
                });
        }, 300);
    });
}
</script>

</body>
</html>