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

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

if (isset($_GET['ajax'])) {

    $q = trim($_GET['q'] ?? '');
    // GET USER COUNTRY FROM SESSION (CORRECT)
        $user_id = $_SESSION['user_id'];

        $stmt = $conn->prepare("SELECT country FROM users WHERE id=?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();

        $userCountry = trim($user['country'] ?? '');

    $where = [];
    $params = [];
    $types = "";

    /* COUNTRY FILTER */
if ($userCountry != '') {
    $where[] = "LOWER(TRIM(country)) LIKE ?";
    $params[] = "%" . strtolower(trim($userCountry)) . "%";
    $types .= "s";
}

    /* SEARCH */
    if ($q != '') {
        $where[] = "(
            LOWER(product_name) LIKE ? OR
            LOWER(generic_name) LIKE ? OR
            LOWER(brand_name) LIKE ?
        )";

        $like = "%" . strtolower($q) . "%";
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
        $types .= "sss";
    }

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

    $sql = "SELECT * FROM sample_products $where_sql ORDER BY id DESC LIMIT 50";

    $stmt = $conn->prepare($sql);

    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }

    $stmt->execute();
    $res = $stmt->get_result();

    $i = 1;
    while($p = $res->fetch_assoc()){
        echo "<tr>
            <td>{$i}</td>
            <td>".htmlspecialchars($p['product_name'])."</td>
            <td>".htmlspecialchars($p['generic_name'])."</td>
            <td>".htmlspecialchars($p['brand_name'])."</td>
            <td>".htmlspecialchars($p['country'])."</td>
            <td>{$p['packet_qty']}</td>
            <td>{$p['units_packet']}</td>
            <td>{$p['price_packet']}</td>
        </tr>";
        $i++;
    }

    exit; // VERY IMPORTANT
}
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 = [];
$messages = [];
$q = $_GET['q'] ?? '';
$q = trim($q);
/* ============================
   USER + COUNTRY
============================ */
$userId = (int)$_SESSION['user_id'];
$userCountry = '';
$userRole = '';

$stmt = $conn->prepare("SELECT role, country FROM users WHERE id=? LIMIT 1");
$stmt->bind_param("i",$userId);
$stmt->execute();
$res = $stmt->get_result();
if($row=$res->fetch_assoc()){
    $userRole = strtolower($row['role']);
    $userCountry = trim($row['country'] ?? '');
}
$stmt->close();

/* ============================
   DELETE SAMPLE PRODUCT
============================ */
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'];

        $stmt = $conn->prepare("SELECT document FROM sample_products WHERE id=?");
        $stmt->bind_param("i",$id);
        $stmt->execute();
        $res = $stmt->get_result();
        $file = $res->fetch_assoc()['document'] ?? '';
        $stmt->close();

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

        if($stmt->execute()){
            if($file){
                $path = __DIR__ . '/../' . $file;
                if(file_exists($path)) unlink($path);
            }
            $messages[] = "Sample product deleted";
        }
        $stmt->close();
    }
}

/* ============================
   SEARCH + FILTER
============================ */
$where = [];
$params = [];
$types = "";

/* AGENCY FILTER */
if (in_array($userRole, ['sales_manager','sales_executive'])) {
    if ($userCountry !== '') {
        $where[] = "LOWER(TRIM(country)) LIKE ?";
        $params[] = "%" . strtolower(trim($userCountry)) . "%";
        $types .= "s";
    } else {
        $where[] = "1=0";
    }
}

/* SEARCH */
if ($q != '') {
    $where[] = "(
        LOWER(product_name) LIKE ? OR
        LOWER(generic_name) LIKE ? OR
        LOWER(brand_name) LIKE ?
    )";

    $like = "%" . strtolower($q) . "%";

    $params[] = $like;
    $params[] = $like;
    $params[] = $like;

    $types .= "sss";
}
$where_sql = $where ? "WHERE ".implode(" AND ",$where) : "";

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

/* ============================
   TOTAL
============================ */
$sql = "SELECT COUNT(*) as total FROM sample_products $where_sql";
$stmt = $conn->prepare($sql);

if($types){
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}}
$stmt->execute();
$total = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();

/* ============================
   FETCH DATA
============================ */
$sql = "SELECT * FROM sample_products
        $where_sql
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);

$params2 = $params;
$params2[] = $limit;
$params2[] = $offset;

$types2 = $types . "ii";

$stmt->bind_param($types2, ...$params2);
$stmt->execute();

$res = $stmt->get_result();

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

$total_pages = ceil($total/$limit);
?>

<!DOCTYPE html>
<html>
<head>
<title>Sample Products</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>

body{
font-family:Inter,Arial;
background:#eef2f7;
margin:0;
padding:40px 25px;
}

/* keep left margin consistent with your sidebar width */
.container{
margin-left:260px;
}

/* CARD */

.card{
background:#fff;
border-radius:14px;
padding:25px;
box-shadow:0 10px 25px rgba(0,0,0,0.05);
}
.page-title{
  display:flex;
  flex-direction:column;
  gap:2px;
}
.page-title h2{
  margin:0;
  font-size:20px;
  display:flex;
  align-items:center;
  gap:8px;
  color:#1e293b;
}

.page-title h2 i{
    font-size: 19px;
  color:#334155;
  font-size:18px;
}

.subtitle{
  margin-top:2px;
  font-size:13px;
  color:#64748b;
  font-weight:500;
}
/* TOP BAR */

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

h2{
margin:0;
font-weight:700;
font-size:20px;
color:#1e293b;
}

/* FILTER */

.filter{
background:#f1f5f9;
padding:10px;
border-radius:12px;
display:flex;
gap:10px;
align-items:center;
margin-bottom:25px;
flex-wrap:wrap;
}

.filter input{
flex:1;
min-width:200px;
padding:10px;
border-radius:8px;
border:1px solid #e2e8f0;
font-size:13.5px;
}

.filter select{
padding:12px;
border-radius:8px;
border:1px solid #e2e8f0;
}

/* BUTTONS */

.btn{
background:#334155;
color:#fff;
padding:8px 14px;
border-radius:20px;
border:none;
cursor:pointer;
font-size:13.5px;
text-decoration:none; /* remove underline */
display:inline-flex;
align-items:center;
gap:6px;
}

.btn:hover{
background:#1e293b;
text-decoration:none; /* keep underline removed on hover */
}
.btn-small{
width:78px;
height:28px;
display:inline-flex;
align-items:center;
justify-content:center;
border-radius:8px;
background:#e2e8f0;
color:#111827;
border:none;
cursor:pointer;
}

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

/* TABLE */

.table{
width:100%;
border-collapse:separate;
border-spacing:0 12px;
}

/* TABLE HEADER */

.table th{
background:#334155;
color:#fff;
padding:10px 12px;
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;
}

/* TABLE ROWS */

.table td{
background:#f8fafc;
padding:12px 14px;
font-size:14.5px;
border-top:1px solid #e2e8f0;
border-bottom:1px solid #e2e8f0;
}

.table tr td:first-child{
border-left:1px solid #e2e8f0;
border-radius:10px 0 0 10px;
}

.table tr td:last-child{
border-right:1px solid #e2e8f0;
border-radius:0 10px 10px 0;
}

.table tr:hover td{
background:#f1f5f9;
}

/* PAGINATION */

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

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

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

/* COLUMN DROPDOWN */

#columnDropdown{
display:none;
position:absolute;
top:35px;
left:0;
background:#fff;
border:1px solid #ddd;
border-radius:10px;
padding:15px;
box-shadow:0 4px 20px rgba(0,0,0,0.1);
width:320px;
z-index:100;
}

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

/* responsive adjustments to keep exact same design but work well on small screens */
@media (max-width:900px) {
  .container{ margin-left:0; padding:20px; }
  body{ padding:20px 12px; }
  .filter{ flex-direction:column; align-items:stretch; }
  .top-bar{ flex-direction:column; gap:12px; align-items:flex-start; }
  .btn{ width:100%; justify-content:center; }
  .table th, .table td { padding:10px; font-size:13px; }
}

/* ADD THIS CSS INSIDE YOUR <style> BELOW EXISTING CSS */

/* ===== Responsive Table Wrapper ===== */

.table-wrapper{
width:100%;
overflow-x:auto;
}

/* Sticky header */

.table thead th{
position:sticky;
top:0;
z-index:2;
}

/* Improve mobile layout */

@media (max-width:900px){

.container{
margin-left:0;
padding:10px;
}

body{
padding:20px 10px;
}

.card{
padding:18px;
}

.top-bar{
flex-direction:column;
align-items:flex-start;
gap:10px;
}

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

.filter input{
width:100%;
}

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

.table{
min-width:900px;
}

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

.export-btn:hover{
background:#15803d;
}
/* FIX TEXT VISIBILITY */

.table td{
    color:#0f172a;   /* dark text */
    font-weight:500;
}

.table th{
    color:#ffffff;   /* keep header white */
}

/* also fix faded rows */
.table tr{
    opacity:1 !important;
}

</style>

</head>

<body>

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

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

<div class="top-bar">
<div class="page-title">
  <h2>
    <i class="fa-solid fa-flask"></i>
    All Sample Products
  </h2>
  <p class="subtitle">View and manage all sample products in your system</p>
</div>
</div>

<form class="filter" method="get">
<input type="search" id="searchInput"
placeholder="Search..."
value="<?php echo e($q); ?>"
autocomplete="off">
<button class="btn-small"><i class="fa fa-search"></i></button>
</form>

<div class="table-wrapper">
<table class="table">

<thead>
<tr>
<th>ID</th>
<th>Product</th>
<th>Generic</th>
<th>Brand</th>
<th>Country</th>
<th>Balance Quantity</th>
<th>Units</th>
<th>Price</th>
</tr>
</thead>

<tbody id="productTable">
<?php if(empty($products)): ?>
<tr>
<td colspan="9" style="text-align:center;">No data found</td>
</tr>
<?php endif; ?>

<?php $index = 0; foreach($products as $p): ?>

<tr>

<td><?php echo $offset + $index + 1; ?></td>

<td><?php echo e($p['product_name']); ?></td>
<td><?php echo e($p['generic_name']); ?></td>
<td><?php echo e($p['brand_name']); ?></td>
<td><?php echo e($p['country']); ?></td>
<td><?php echo e($p['packet_qty']); ?></td>
<td><?php echo e($p['units_packet']); ?></td>
<td><?php echo e($p['price_packet']); ?></td>

</tr>

<?php $index++; endforeach; ?>
</tbody>
</table>
</div>

<!-- PAGINATION -->
<div class="pagination">
<?php for($i=1;$i<=$total_pages;$i++): ?>
<a href="?page=<?php echo $i; ?>&q=<?php echo urlencode($q); ?>">
<?php echo $i; ?>
</a>
<?php endfor; ?>
</div>

</div>
</div>
<script>

let timer;

document.getElementById("searchInput").addEventListener("keyup", function(){

    clearTimeout(timer);

    let query = this.value;

    timer = setTimeout(() => {

        fetch("?ajax=1&q=" + encodeURIComponent(query))
        .then(res => res.text())
        .then(data => {
            document.getElementById("productTable").innerHTML = data;
        });

    }, 300); // debounce

});

</script>
</body>
</html>