<?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); }

/* ===== ROLE ===== */
$user_id = $_SESSION['user_id'];
$role = strtolower($_SESSION['role'] ?? '');

/* 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'];

        // 👉 RA cannot delete others data (optional restriction)
        if($role !== 'admin'){
            $check = $conn->query("SELECT id FROM sample_products WHERE id=$id AND created_by=$user_id");
            if(!$check->num_rows){
                die("Unauthorized");
            }
        }

        $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 ================= */
if (isset($_GET['export'])) {

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

    // 👉 Admin = all, RA = own
    if($role === 'admin'){
        $res = $conn->query("SELECT * FROM sample_products");
    } else {
        $res = $conn->query("SELECT * FROM sample_products WHERE created_by=$user_id");
    }

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

    while ($r = $res->fetch_assoc()) {
        echo "{$r['id']}\t{$r['product_name']}\t{$r['generic_name']}\t{$r['brand_name']}\t{$r['country']}\t{$r['price_packet']}\n";
    }
    exit;
}

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

$where = "WHERE 1";

/* 👉 ROLE FILTER */
if($role !== 'admin'){
    $where .= " AND created_by=$user_id";
}

if ($q != '') {
    $q = $conn->real_escape_string($q);
    $where .= " AND (product_name LIKE '%$q%' OR generic_name LIKE '%$q%' OR brand_name LIKE '%$q%')";
}

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

/* ================= PAGINATION ================= */
$page = max(1,(int)($_GET['page'] ?? 1));
$per_page = 15;
$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{
    --bg:#f3f6fb;
    --card:#ffffff;
    --text:#111827;
    --muted:#6b7280;
    --line:#e5e7eb;
    --line-2:#dbe3ee;

    --primary:#374155;
    --primary-2:#1f2937;

    --blue:#2563eb;
    --blue-2:#1d4ed8;

    --green:#16a34a;
    --green-2:#15803d;

    --red:#dc2626;
    --red-2:#b91c1c;

    --shadow:0 14px 40px rgba(15,23,42,.08);
    --shadow-soft:0 8px 20px rgba(15,23,42,.06);
    --radius:20px;
    --sidebar:260px;
}

*{
    box-sizing:border-box;
}

html,body{
    margin:0;
    padding:0;
    font-family:Inter, Arial, Helvetica, sans-serif;
    background:
        radial-gradient(circle at top left, rgba(55,65,85,.06), transparent 32%),
        radial-gradient(circle at top right, rgba(37,99,235,.06), transparent 28%),
        var(--bg);
    color:var(--text);
}

/* MAIN WRAPPER */
.container{
    margin-left:var(--sidebar);
    padding:70px 14px 14px;
}

/* CARD */
.card{
    background:rgba(255,255,255,.92);
    border:1px solid rgba(229,231,235,.9);
    border-radius:16px;
    box-shadow:var(--shadow);
    overflow:hidden;
    backdrop-filter: blur(6px);
    -webkit-backdrop-filter: blur(6px);
    padding:14px;
}

/* TOP HEADER AREA */
.card > div:first-child{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:16px;
    flex-wrap:wrap;
    padding-bottom:18px;
    margin-bottom:18px;
    border-bottom:1px solid var(--line);
}

.card h2{
    margin:0;
    font-size:20px;
    line-height:1.2;
    font-weight:800;
    letter-spacing:-0.02em;
    color:#0f172a;
}

.card h2 i{
    margin-right:10px;
    color:var(--primary);
}

.card > div:first-child > div:first-child > div{
    margin-top:6px;
    color:var(--muted);
    font-size:14px;
}

/* ADD BUTTON */
.add-btn{
    display:inline-flex;
    align-items:center;
    gap:8px;
    height:34px;
    padding:0 12px;
    border-radius:10px;
    background:#374155;
    color:#fff;
    text-decoration:none;
    font-size:12px;
    font-weight:700;
    box-shadow:0 10px 22px rgba(37,99,235,.22);
    transition:.2s ease;
    white-space:nowrap;
}

.add-btn:hover{
    transform:translateY(-1px);
    box-shadow:0 14px 26px rgba(37,99,235,.28);
}

/* FILTER BAR */
.filter-bar{
    display:flex;
    align-items:center;
    gap:6px;
    flex-wrap:wrap;
    padding:0 0 16px;
    margin:0 0 8px;
}

.filter-bar input,
.filter-bar select{
    height:34px;
    border:1px solid var(--line-2);
    border-radius:10px;
    background:#fff;
    padding:0 10px;
    font-size:12px;
    color:var(--text);
    outline:none;
    transition:.2s ease;
    box-shadow:0 1px 0 rgba(15,23,42,.02);
}

.filter-bar input{
    min-width:260px;
    flex:1 1 280px;
}

.filter-bar select{
    min-width:180px;
    flex:0 0 180px;
}

.filter-bar input:focus,
.filter-bar select:focus{
    border-color:rgba(37,99,235,.55);
    box-shadow:0 0 0 4px rgba(37,99,235,.10);
}
.card h2 + div{
    font-size:12px;
}

.filter-btn{
    height:42px;
    padding:0 16px;
    border:none;
    border-radius:14px;
    background:var(--primary);
    color:#fff;
    font-size:14px;
    font-weight:700;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:8px;
    transition:.2s ease;
    box-shadow:0 10px 20px rgba(55,65,85,.14);
}

.filter-btn:hover{
    background:var(--primary-2);
    transform:translateY(-1px);
}

/* MESSAGE */
.msg{
    margin:0 0 14px;
    padding:12px 14px;
    border-radius:14px;
    background:#ecfdf5;
    color:#166534;
    border:1px solid #bbf7d0;
    font-size:14px;
    font-weight:600;
}

/* TABLE WRAP */
.table{
    width:100%;
    border-collapse:separate;
    border-spacing:0;
    min-width:1200px;
    overflow:hidden;
    border-radius:18px;
}

/* HEADER */
.table thead th{
    padding:8px 12px;
    font-size:11px;
    white-space: nowrap;
}

.table th:last-child,
.table td:last-child{
    min-width:120px;
    text-align:center;
}
.table th:nth-last-child(2),
.table td:nth-last-child(2){
    min-width:70px;
    text-align:center;
}
.table tr:first-child th{
    position:sticky;
    top:0;
    z-index:2;
    background:linear-gradient(180deg,var(--primary),var(--primary-2));
    color:#fff;
    padding:14px 12px;
    font-size:13px;
    font-weight:700;
    text-align:left;
    white-space:nowrap;
    border-bottom:1px solid rgba(255,255,255,.08);
}

/* BODY */
.table tbody td{
    padding:8px 8px;
    font-size:12px;
    vertical-align:middle;
    border-bottom:1px solid #eef2f7;
    background:#fff;
    color:#0f172a;
}

.table tbody tr:nth-child(even) td{
    background:#fafcff;
}

.table tbody tr:hover td{
    background:#f4f8ff;
}

/* FIRST COLUMN ALIGNMENT */
.table td:first-child,
.table th:first-child{
    width:70px;
    text-align:center;
}

/* DATE COLUMN */
.table td:nth-child(2){
    white-space:nowrap;
    color:#334155;
}

/* EDITABLE CELLS */
.editable{
    border-radius:10px;
    outline:none;
    transition:.15s ease;
    cursor:text;
}

.editable:hover{
    background:#eef6ff;
}

.editable:focus{
    background:#eff6ff;
    box-shadow:inset 0 0 0 1px rgba(37,99,235,.25);
}

.editable.saved{
    background:#ecfdf5 !important;
    box-shadow:inset 0 0 0 1px rgba(22,163,74,.25);
}

.editable.error{
    background:#fef2f2 !important;
    box-shadow:inset 0 0 0 1px rgba(220,38,38,.3);
}

/* ACTION AREA */
.table td:last-child{
    white-space:nowrap;
}

.table td:last-child > div{
    display:flex !important;
    gap:6px;
    align-items:center;
}

/* SMALL ICON BUTTON */
.btn-small{
    width:30px;
    height:30px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:8px;
    border:none;
    color:#fff;
    text-decoration:none;
    cursor:pointer;
    transition:.2s ease;
    box-shadow:0 8px 18px rgba(15,23,42,.12);
    background:var(--primary);
    flex:0 0 auto;
}

.btn-small i{
    font-size:11px;
    line-height:1;
}

.btn-small:hover{
    transform:translateY(-2px);
    box-shadow:0 12px 20px rgba(15,23,42,.16);
}

/* EDIT */
a.btn-small{
    background:linear-gradient(180deg,#2563eb,#1d4ed8);
}

/* DELETE */
form .btn-small{
    background:linear-gradient(180deg,#dc2626,#b91c1c);
}

/* FILE BUTTON */
td a.btn-small[href*="../uploads/"]{
    background:linear-gradient(180deg,#0f766e,#0f5f59);
}

/* PAGINATION */
.pagination{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
    padding:18px 0 4px;
    align-items:center;
}

.pagination a{
    min-width:32px;
    height:32px;
    padding:0 10px;
    border-radius:12px;
    border:1px solid var(--line-2);
    background:#fff;
    color:#0f172a;
    text-decoration:none;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    font-size:12px;
    font-weight:600;
    transition:.2s ease;
}

.pagination a:hover{
    border-color:rgba(37,99,235,.35);
    box-shadow:0 8px 18px rgba(15,23,42,.06);
    transform:translateY(-1px);
}

.pagination a.active{
    background:linear-gradient(180deg,var(--primary),var(--primary-2));
    color:#fff;
    border-color:transparent;
}

/* RESPONSIVE */
@media (max-width: 1100px){
    .container{
        margin-left:0;
        padding:18px;
    }

    .card{
        padding:18px;
    }

    .card > div:first-child{
        align-items:flex-start;
    }
}

@media (max-width: 768px){
    .card h2{
        font-size:22px;
    }

    .filter-bar input{
        min-width:100%;
        flex:1 1 100%;
    }

    .filter-bar select{
        min-width:100%;
        flex:1 1 100%;
    }

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

    .table{
        min-width:1050px;
    }

    .card{
        padding:14px;
        border-radius:18px;
    }
}

/* NICE SCROLLBAR */
.card::-webkit-scrollbar,
.table::-webkit-scrollbar{
    height:10px;
    width:10px;
}

.card::-webkit-scrollbar-track,
.table::-webkit-scrollbar-track{
    background:#f1f5f9;
}

.card::-webkit-scrollbar-thumb,
.table::-webkit-scrollbar-thumb{
    background:#cbd5e1;
    border-radius:999px;
}

.card::-webkit-scrollbar-thumb:hover,
.table::-webkit-scrollbar-thumb:hover{
    background:#94a3b8;
}
/* ================= MOBILE RESPONSIVE ================= */
@media (max-width: 768px) {

    /* HEADER FIX */
    body {
        padding-top: 65px;
    }

    /* CONTAINER FULL WIDTH */
    .container {
        margin-left: 0 !important;
        padding: 12px;
    }

    /* HEADER AREA */
    .card > div:first-child {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .card h2 {
        font-size: 18px;
    }

    /* ADD BUTTON */
    .add-btn {
        width: 100%;
        justify-content: center;
    }

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

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

    /* TABLE SCROLL (IMPORTANT) */
    .table {
        display: block;
        overflow-x: auto;
        min-width: 1000px;
    }

    /* TABLE TEXT */
    .table th,
    .table td {
        font-size: 12px;
        padding: 8px;
        white-space: nowrap;
    }

    /* ACTION BUTTONS */
    .table td:last-child > div {
        flex-direction: column;
        gap: 6px;
    }

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

    .pagination a {
        font-size: 11px;
        padding: 6px 10px;
    }
}
/* ===== MOBILE FILTER IMPROVEMENT ===== */
@media (max-width: 768px) {

    .filter-bar {
        display: flex;
        flex-direction: column;
        gap: 10px;
        padding: 10px;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    }

    .filter-bar input,
    .filter-bar select {
        width: 100%;
        height: 42px;
        border-radius: 10px;
        border: 1px solid #e5e7eb;
        padding: 0 12px;
        font-size: 14px;
        background: #f9fafb;
    }

    .filter-bar input:focus,
    .filter-bar select:focus {
        border-color: #374155;
        background: #fff;
        box-shadow: 0 0 0 3px rgba(55,65,85,0.1);
    }

    .filter-btn {
        width: 100%;
        height: 42px;
        border-radius: 10px;
        font-size: 14px;
        justify-content: center;
        background: #374155;
    }

}
</style>
</head>

<body>

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

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

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:10px;">

    <div>
        <h2 style="margin:0;font-size:22px;font-weight:700;">
            <i class="fa fa-box"></i> All Sample Product
        </h2>
        <div style="color:#64748b;font-size:14px;margin-top:4px;">
            Manage, search, filter, and update all sample products in one place.
        </div>
    </div>

    <a href="sample-product.php" class="add-btn">
    <i class="fa fa-plus"></i> Add Product
</a>

</div>

<form class="filter-bar">

    <input type="text" id="liveSearch" name="q"
        placeholder="Search product..."
        value="<?php echo e($q); ?>">

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

    <button type="submit" class="filter-btn">
        <i class="fa fa-filter"></i> Filter
    </button>

</form>

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

<table class="table">
<tr>
<th>No.</th>
<th>Date</th>
<th>Product</th>
<th>Generic</th>
<th>Brand</th>
<th>Country</th>
<th>Balance Quantity</th>
<th>Units</th>
<th>Price</th>
<th>File</th>
<th>Action</th>
</tr>

<?php $i = 1 + $offset; ?>
<?php foreach($products as $p): ?>
<tr>

<td><?php echo $i++; ?></td>
<td>
<?php 
echo !empty($p['created_at']) 
    ? date('d M Y', strtotime($p['created_at'])) 
    : '-'; 
?>
</td>

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

<td contenteditable="true" class="editable" data-id="<?=$p['id']?>" data-field="generic_name"><?=e($p['generic_name'])?></td>

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

<td contenteditable="true" class="editable" data-id="<?=$p['id']?>" data-field="country"><?=e($p['country'])?></td>

<td contenteditable="true" class="editable number" data-id="<?=$p['id']?>" data-field="packet_qty"><?=$p['packet_qty']?></td>

<td contenteditable="true" class="editable number" data-id="<?=$p['id']?>" data-field="units_packet"><?=$p['units_packet']?></td>

<td contenteditable="true" class="editable number" data-id="<?=$p['id']?>" data-field="price_packet"><?=$p['price_packet']?></td>


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

<td>
<div style="display:flex; gap:6px; align-items:center;">

<!-- EDIT BUTTON -->
<a class="btn-small" href="sample-product.php?id=<?php echo $p['id']; ?>">
    <i class="fa fa-pen"></i>
</a>

<!-- DELETE BUTTON -->
<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; ?>

</table>
<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 $country; ?>">
<?php echo $i; ?>
</a>
<?php endfor; ?>
</div>

</div>
</div>
<script>

document.querySelectorAll(".editable").forEach(cell => {

    cell.addEventListener("keydown", function(e){
        if(e.key === "Enter"){
            e.preventDefault();
            this.blur();
        }
    });

    cell.addEventListener("blur", function(){

        let id = this.dataset.id;
        let field = this.dataset.field;
        let value = this.innerText.trim();

        /* NUMBER VALIDATION */
        if(this.classList.contains("number") && isNaN(value)){
            this.classList.add("error");
            return;
        }

        fetch("inline-update.php", {
            method:"POST",
            headers:{
                "Content-Type":"application/x-www-form-urlencoded"
            },
            body:`id=${id}&field=${field}&value=${encodeURIComponent(value)}`
        })
        .then(res=>res.text())
        .then(res=>{

            if(res === "OK"){
                this.classList.add("saved");
                setTimeout(()=>this.classList.remove("saved"),1000);
            }else{
                this.classList.add("error");
            }

        });

    });

});

</script>
<script>
let timer;

document.getElementById("liveSearch").addEventListener("keyup", function(){
    clearTimeout(timer);

    timer = setTimeout(() => {
        let q = this.value;
        let url = new URL(window.location.href);

        url.searchParams.set("q", q);
        url.searchParams.set("page", 1);

        window.location.href = url;
    }, 400);
});
</script>
</body>
</html>