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

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

function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }

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

$errors = [];
$msg = "";

/* ================= DELETE ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {

    if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $errors[] = "Invalid request";
    } else {

        $id = (int)$_POST['delete_id'];

        $res = $conn->query("SELECT document FROM sample_products WHERE id=$id");
        $row = $res->fetch_assoc();

        $conn->query("DELETE FROM sample_products WHERE id=$id");

        if (!empty($row['document'])) {
            $file = "../uploads/".$row['document'];
            if (file_exists($file)) unlink($file);
        }

        $msg = "Product deleted!";
    }
}

/* ================= EXPORT EXCEL ================= */
if (isset($_GET['export'])) {

    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=sample_products.xls");

    $res = $conn->query("SELECT * FROM sample_products");

    echo "ID\tProduct\tGeneric\tBrand\tCountry\tPrice\n";

   echo "ID\tProduct\tBrand\tPacking\tBatch No\tMfg Date\tExpiry Date\tManufactured By\tReceived On\tReceived By\tReceived Qty\tSent On\tSent By\tSent To\tSent Qty\tRemaining Qty\tTracking No\tComments\tCountry\n";

while ($r = $res->fetch_assoc()) {
    echo $r['id']."\t".
         $r['product_name']."\t".
         $r['brand_name']."\t".
         $r['packing']."\t".
         $r['batch_no']."\t".
         $r['manufacturing_date']."\t".
         $r['expiry_date']."\t".
         $r['manufactured_by']."\t".
         $r['received_on']."\t".
         $r['received_by']."\t".
         $r['received_qty']."\t".
         $r['sent_on']."\t".
         $r['sent_by']."\t".
         $r['sent_to']."\t".
         $r['sent_qty']."\t".
         $r['remaining_qty']."\t".
         $r['tracking_number']."\t".
         $r['comments']."\t".
         $r['country']."\n";
}
    exit;
}

/* ================= FILTER ================= */
$q = trim($_GET['q'] ?? '');
$country = $_GET['country'] ?? '';

$where = "WHERE 1";

if ($q != '') {
    $q = $conn->real_escape_string($q);
    $where .= " AND (
        product_name LIKE '%$q%' OR
        brand_name LIKE '%$q%' OR
        packing LIKE '%$q%' OR
        batch_no LIKE '%$q%' OR
        manufactured_by LIKE '%$q%' OR
        received_by LIKE '%$q%' OR
        sent_by LIKE '%$q%' OR
        sent_to LIKE '%$q%' OR
        tracking_number LIKE '%$q%' OR
        comments LIKE '%$q%'
    )";
}

if ($country != '') {
    $country = $conn->real_escape_string($country);
    $where .= " AND country='$country'";
}

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

$total = $conn->query("SELECT COUNT(*) as t FROM sample_products $where")->fetch_assoc()['t'];
$total_pages = ceil($total/$per_page);

/* ================= DATA ================= */
$res = $conn->query("SELECT * FROM sample_products $where ORDER BY id DESC LIMIT $per_page OFFSET $offset");

$products = [];
while($r = $res->fetch_assoc()){
    $products[] = $r;
}

/* ================= COUNTRIES ================= */
$countries = [];
$res = $conn->query("SELECT DISTINCT country FROM sample_products ORDER BY country");
while($r = $res->fetch_assoc()){
    $countries[] = $r['country'];
}
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sample Products</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>

:root{
--primary:#2563eb;
--primary-dark:#1d4ed8;
--bg:#f4f7fb;
--card:#ffffff;
--text:#0f172a;
--muted:#64748b;
--border:#e5e7eb;
--danger:#dc2626;
}

/* ===== BODY ===== */
body{
margin:0;
font-family:Inter,Segoe UI,Arial,sans-serif;
background:
radial-gradient(circle at top left, rgba(37,99,235,.08), transparent 22%),
radial-gradient(circle at top right, rgba(15,23,42,.06), transparent 20%),
var(--bg);
padding:80px 24px 30px;
color:var(--text);
}

/* ===== LAYOUT ===== */
.container{
margin-left:260px;
}

/* ===== CARD ===== */
.card{
background:rgba(255,255,255,.92);
backdrop-filter:blur(8px);
border:1px solid rgba(229,231,235,.9);
border-radius:24px;
box-shadow:0 18px 50px rgba(15,23,42,.10);
padding:30px;
}

/* ===== TOP BAR ===== */
.top-bar{
display:flex;
justify-content:space-between;
align-items:center;
margin-bottom:25px;
}

h2{
margin:0;
font-size:26px;
font-weight:800;
letter-spacing:-.02em;
}

/* ===== FILTER ===== */
.filter{
background:#f8fafc;
padding:14px;
border-radius:14px;
display:flex;
gap:10px;
margin-bottom:20px;
border:1px solid var(--border);
}

.filter input,
.filter select{
padding:12px 14px;
border-radius:12px;
border:1px solid var(--border);
font-size:14px;
background:#fff;
}

.filter input:focus,
.filter select:focus{
border-color:#000;
outline:none;
}

/* ===== BUTTON ===== */
.btn{
background:#000;
color:#fff;
padding:12px 18px;
border-radius:14px;
text-decoration:none;
font-weight:700;
display:inline-flex;
align-items:center;
gap:8px;
transition:.2s;
}

.btn:hover{
transform:translateY(-1px);
background:linear-gradient(135deg,var(--primary-dark),#2563eb);
}

/* SMALL BUTTON */
.btn-small{
background:#e2e8f0;
padding:7px 10px;
border-radius:8px;
display:flex;
align-items:center;
justify-content:center;
border:none;
cursor:pointer;
color:#111827;
}

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

/* ===== TABLE ===== */
.table{
    width:max-content;
    min-width:100%;
    border-collapse:collapse;   /* ✅ IMPORTANT */
}

.table-wrapper{
    width:100%;
    overflow-x:auto;
}
/* HEADER */
.table th{
background:#374155;
color:#fff;
padding:14px;
font-size:13px;
text-align:left;
}

.table th:first-child{
border-radius:10px 0 0 10px;
}
.table th:last-child{
border-radius:0 10px 10px 0;
}

/* ROW */
.table td{
background:#f9fbfd;
padding:14px;
font-size:14px;
border-top:1px solid var(--border);
border-bottom:1px solid var(--border);
}

/* ROUNDED ROW */
.table td:first-child{
border-left:1px solid var(--border);
border-radius:10px 0 0 10px;
}
.table td:last-child{
border-right:1px solid var(--border);
border-radius:0 10px 10px 0;
}

/* HOVER */
.table tr:hover td{
background:#eef2f7;
}

/* ===== PAGINATION ===== */
.pagination{
margin-top:20px;
display:flex;
gap:8px;
}

.pagination a{
padding:8px 12px;
border-radius:10px;
border:1px solid var(--border);
background:#fff;
text-decoration:none;
font-size:13px;
}

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

/* ===== MESSAGE ===== */
.msg{
background:#dcfce7;
color:#166534;
padding:12px;
border-radius:10px;
margin-bottom:15px;
font-weight:600;
}

/* ===== INLINE EDIT ===== */
.editable{
cursor:pointer;
transition:.2s;
border-radius:6px;
}

.editable:hover{
background:#eef6ff;
}

.editable:focus{
    outline:none !important;
    background:transparent !important;
}

/* SAVED */
.saved{
background:#dcfce7 !important;
}

/* ERROR */
.error{
background:#fee2e2 !important;
}

/* ===== RESPONSIVE ===== */
@media(max-width:992px){
.container{margin-left:0;}
body{padding:70px 15px;}
.filter{flex-direction:column;}
}
/* ================= MOBILE RESPONSIVE ================= */
@media (max-width:768px){

    /* ðŸ”¥ REMOVE SIDEBAR GAP */
    .container{
        margin-left:0 !important;
        padding:10px;
    }

    body{
        padding:65px 10px;
    }

    /* TOP BAR */
    .top-bar{
        flex-direction:column;
        align-items:stretch;
        gap:10px;
    }

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

    /* FILTER */
    .filter{
        flex-direction:column;
        gap:8px;
    }

    .filter input,
    .filter select{
        width:100%;
    }

    /* ðŸ”¥ TABLE â†’ CARD */
    .table thead{
        display:none;
    }

    .table{
        border-spacing:0;
    }

    .table tbody tr{
        display:block;
        background:#fff;
        margin-bottom:12px;
        border-radius:12px;
        padding:12px;
        box-shadow:0 4px 10px rgba(0,0,0,0.05);
    }

    .table tbody td{
        display:flex;
        justify-content:space-between;
         line-height:1.4;
        align-items:center;
        padding:8px 0;
        border:none;
        font-size:13px;
        gap:10px;
    }

    .table tbody td::before{
        content:attr(data-label);
        font-size:12px;
        font-weight:600;
        color:#64748b;
        flex:0 0 45%;
    }
.table tbody td:first-child{
        font-weight:700;
    /* ACTION */
    .table tbody td:last-child div{
        justify-content:flex-end;
        width:100%;
    }

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

}
</style>
</head>

<body>

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

<div class="container">
<div class="card">

<div class="top-bar">
    <h2>Sample Products</h2>

    <a href="?export=1" class="btn">
        <i class="fa fa-file-excel"></i> Export Excel
    </a>
</div>

<div class="filter">
    <input type="text" id="liveSearch" placeholder="Search...">

    <select id="countryFilter">
        <option value="">All Country</option>
        <?php foreach($countries as $c): ?>
        <option value="<?php echo e($c); ?>" <?php if($country==$c) echo "selected"; ?>><?php echo e($c); ?></option>
        <?php endforeach; ?>
    </select>

</div>


<?php if($msg): ?><div class="msg"><?php echo $msg; ?></div><?php endif; ?>

<div class="table-wrapper"> <table class="table">
<thead>
<tr>
    <th>No.</th>
    <th>Product</th>
    <th>Brand</th>
    <th>Packing</th>
    <th>Batch No</th>
    <th>Mfg Date</th>
    <th>Expiry Date</th>
    <th>Manufactured By</th>
    <th>Received On</th>
    <th>Received By</th>
    <th>Received Qty</th>
    <th>Sent On</th>
    <th>Sent By</th>
    <th>Sent To</th>
    <th>Sent Qty</th>
    <th>Remaining Qty</th>
    <th>Tracking No</th>
    <th>Comments</th>
    <th>File</th>
    <th>Action</th>
</tr>
</thead>

<tbody>
<?php $i = $offset + 1; foreach($products as $p): ?>
<tr>
    <td data-label="No."><?= $i++; ?></td>

    <td data-label="Product" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="product_name"><?= e($p['product_name']) ?></td>

    <td data-label="Brand" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="brand_name"><?= e($p['brand_name']) ?></td>

    <td data-label="Packing" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="packing"><?= e($p['packing']) ?></td>

    <td data-label="Batch No" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="batch_no"><?= e($p['batch_no']) ?></td>

    <td data-label="Mfg Date" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="manufacturing_date"><?= e($p['manufacturing_date']) ?></td>

    <td data-label="Expiry Date" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="expiry_date"><?= e($p['expiry_date']) ?></td>

    <td data-label="Manufactured By" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="manufactured_by"><?= e($p['manufactured_by']) ?></td>

    <td data-label="Received On" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="received_on"><?= e($p['received_on']) ?></td>

    <td data-label="Received By" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="received_by"><?= e($p['received_by']) ?></td>

    <td data-label="Received Qty" contenteditable="false" class="editable number"
        data-id="<?= $p['id'] ?>" data-field="received_qty"><?= e($p['received_qty']) ?></td>

    <td data-label="Sent On" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="sent_on"><?= e($p['sent_on']) ?></td>

    <td data-label="Sent By" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="sent_by"><?= e($p['sent_by']) ?></td>

    <td data-label="Sent To" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="sent_to"><?= e($p['sent_to']) ?></td>

    <td data-label="Sent Qty" contenteditable="false" class="editable number"
        data-id="<?= $p['id'] ?>" data-field="sent_qty"><?= e($p['sent_qty']) ?></td>

    <td data-label="Remaining Qty" contenteditable="false" class="editable number"
        data-id="<?= $p['id'] ?>" data-field="remaining_qty"><?= e($p['remaining_qty']) ?></td>

    <td data-label="Tracking No" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="tracking_number"><?= e($p['tracking_number']) ?></td>

    <td data-label="Comments" contenteditable="false" class="editable"
        data-id="<?= $p['id'] ?>" data-field="comments"><?= e($p['comments']) ?></td>

    <td data-label="File">
        <?php if($p['document']): ?>
            <a class="btn-small" href="../uploads/<?php echo e($p['document']); ?>" target="_blank">
                <i class="fa fa-file"></i>
            </a>
        <?php endif; ?>
    </td>

    <td data-label="Action">
        <div style="display:flex; gap:6px;">
            <a class="btn-small" href="sample-product.php?id=<?php echo $p['id']; ?>">
                <i class="fa fa-pen"></i>
            </a>

            <form method="post" style="display:inline">
                <input type="hidden" name="csrf_token" value="<?php echo $csrf; ?>">
                <input type="hidden" name="delete_id" value="<?php echo $p['id']; ?>">
                <button class="btn-small" onclick="return confirm('Delete this product?')">
                    <i class="fa fa-trash"></i>
                </button>
            </form>
        </div>
    </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="pagination">
<?php for($i=1;$i<=$total_pages;$i++): ?>
<a href="?page=<?php echo $i; ?>&q=<?php echo urlencode($q); ?>&country=<?php echo urlencode($country); ?>">
<?php echo $i; ?>
</a>
<?php endfor; ?>
</div>

</div>
</div>
<script>

// disable inline editing completely
document.querySelectorAll(".editable").forEach(cell => {
    cell.removeAttribute("contenteditable");
});
function filterTable(){

    let search = document.getElementById("liveSearch").value.toLowerCase();
    let country = document.getElementById("countryFilter").value.toLowerCase();

    let rows = document.querySelectorAll(".table tbody tr");

    rows.forEach(row => {

        let text = row.innerText.toLowerCase();
        let countryText = row.children[4].innerText.toLowerCase().trim();

        let matchSearch = text.includes(search);
        let matchCountry = (country === "" || countryText === country);

        if(matchSearch && matchCountry){
            row.style.display = "";
        } else {
            row.style.display = "none";
        }

    });

}

/* EVENTS */
document.getElementById("liveSearch").addEventListener("keyup", filterTable);
document.getElementById("countryFilter").addEventListener("change", filterTable);
</script>
</body>
</html>