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

/* ✅ ADD THIS FUNCTION (FROM MANAGER) */
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");

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

/* ✅ GET USER COUNTRY */
$session_user_id = (int)($_SESSION['user_id'] ?? 0);
$session_country = '';

if ($session_user_id > 0) {
    $stmt = $conn->prepare("SELECT country FROM users WHERE id = ?");
    $stmt->bind_param("i", $session_user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $session_country = trim($row['country']);
    }
    $stmt->close();
}

/* ✅ ALL COLUMNS */
 $allowed_columns = [
    
        /* Commercial Product Info */
        'product_name' => 'Product Name',
        'generic_name' => 'Generic Name',
        'brand_name' => 'Brand Name',
        'country' => 'Country',
        '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 */
$selected_columns = $_GET['columns'] ?? [
'product_name',
'brand_name',
'country',
'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'];
}

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

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

/* ✅ WHERE START */
$where = "WHERE status='approved'";
$params=[];
$types="";

/* ✅ COUNTRY FILTER */
$country_id = find_country_id_for_user($conn, $session_country);

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

/* ✅ SEARCH FIX */
if($q!=''){
    $where .= " AND product_name LIKE ?";
    $params[] = "%$q%";
    $types .= "s";
}

/* COUNT */
$sql_count="SELECT COUNT(*) as total FROM products $where";
$stmt=$conn->prepare($sql_count);

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

$stmt->execute();
$total=$stmt->get_result()->fetch_assoc()['total'];
$stmt->close();

/* DATA */
$sql="SELECT * FROM products $where ORDER BY created_at DESC LIMIT ? OFFSET ?";
$stmt=$conn->prepare($sql);

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

$types2=$types."ii";

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

$result=$stmt->get_result();
$products=$result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

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

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>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, sans-serif;
    background: #fff;
    margin: 0;
    padding: 0;
    color: #111827;
}

.container{
    margin-left: 260px;
    padding: 40px 20px 20px;
}

.page-title{
    display:flex;
    align-items:center;
    gap:10px;
    margin: 0 0 16px;
    font-size: 22px;
    margin-bottom: 12px;
    font-weight: 800;
    color: #0f172a;
}

.page-title i{
    color:#334155;
    font-size: 20px;
}

.card{
    background: rgba(255,255,255,0.95);
    border: 1px solid rgba(226,232,240,0.9);
    border-radius: 16px;
    padding: 16px;
  box-shadow: 0 8px 24px rgba(15,23,42,.08)
}

.search-box{
    margin-bottom: 18px;
}

.search-wrapper{
    background: linear-gradient(135deg, #ffffff, #f8fbff);
    border: 1px solid #e2e8f0;
    border-radius: 14px;
    padding: 12px;
    display:flex;
    justify-content:space-between;
    align-items:end;
    gap:12px;
    flex-wrap:wrap;
}

.search-left{
    flex:1;
    min-width: 260px;
}

.search-left label{
    display:block;
    font-weight:700;
    margin-bottom:8px;
    color:#334155;
}

.search-left input{
    width:100%;
    padding:10px 12px;
    border-radius:12px;
    border:1px solid #dbe4ee;
    outline:none;
    font-size:13px;
    background:#fff;
}

.search-left input:focus{
    border-color:#2563eb;
    box-shadow:0 0 0 3px rgba(37,99,235,.12);
}

.search-right{
    display:flex;
    align-items:center;
    gap:10px;
    flex-wrap:wrap;
}

.search-btn{
    background:#334155;
    color:#fff;
    border:none;
    padding:10px 14px;
    border-radius:12px;
    cursor:pointer;
    display:flex;
    align-items:center;
    gap:8px;
    font-size:13px;
    font-weight:700;
    box-shadow:0 8px 18px rgba(37,99,235,.18);
}

.search-btn:hover{
    transform: translateY(-1px);
}

.count-badge{
    background:#334155;
    color:#fff;
    padding:8px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
}

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

.btn-small:hover{
    background:#1e293b;
}

#columnDropdown{
    display:none;
    position:absolute;
    top:48px;
    left:0;
    background:#fff;
    color:#000;
    padding:16px;
    border-radius:14px;
    box-shadow:0 12px 32px rgba(0,0,0,.12);
    width:380px;
    z-index:100;
    border:1px solid #e2e8f0;
}

.column-grid{
    display:grid;
    grid-template-columns:repeat(2,1fr);
    gap:8px;
    max-height:260px;
    overflow:auto;
    font-size:14px;
}

.column-grid label{
    display:flex;
    align-items:center;
    gap:8px;
    padding:6px 8px;
    border-radius:8px;
    background:#f8fafc;
}

.table{
    background-color: #334155;
    width:100%;
    border-collapse:separate;
    border-spacing:0;
    overflow:hidden;
    border-radius:16px;
}

.table thead th{
    background: #334155;
    color:#fff;
    padding:12px 10px;
     font-size:13px;
    font-weight:700;
    text-align:left;
    white-space:nowrap;
}

.table tbody td{
    background:#fff;
    padding:11px 10px;
    font-size:13px;
    color:#111827;
    border-bottom:1px solid #eef2f7;
    vertical-align:middle;
}

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

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

.pagination a{
    padding:7px 11px;
    font-size:12px;
    border:1px solid #dbe4ee;
    border-radius:10px;
    text-decoration:none;
    color:#334155;
    background:#fff;
    font-weight:700;
}

.pagination a:hover{
    background:#374155;
    color:#fff;
    border-color:#2563eb;
}

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

/* ================= MOBILE RESPONSIVE (NO HORIZONTAL SCROLL) ================= */
@media (max-width: 768px){

    .container{
        margin-left: 0 !important;
        padding: 12px !important;
        width: 100%;
    }

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

    .search-wrapper{
        flex-direction: column;
        align-items: stretch;
        gap: 10px;
    }

    .search-left,
    .search-right{
        width: 100%;
    }

    .search-right{
        flex-direction: column;
        gap: 8px;
    }

    .search-btn,
    .count-badge{
        width: 100%;
        justify-content: center;
    }

    #columnDropdown{
        width: 100%;
        left: 0;
        right: 0;
    }

    .column-grid{
        grid-template-columns: 1fr;
    }

    /* table full width, no horizontal scroll */
    .table{
        width: 100%;
        display: table;
        table-layout: fixed;
        border-collapse: collapse;
    }

    .table thead th,
    .table tbody td{
        white-space: normal;
        word-break: break-word;
        overflow-wrap: anywhere;
        font-size: 11px;
        padding: 6px 5px;
        vertical-align: top;
    }

    .table thead th{
        line-height: 1.25;
    }

    .pagination{
        justify-content: center;
        gap: 6px;
    }

    .pagination a{
        font-size: 11px;
        padding: 6px 10px;
    }
}
</style>
</head>

<body>

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

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

  <h2 class="page-title" style="color:#000;">
    <i class="fa fa-boxes-stacked"></i>
   All Commercial Products
</h2>
<p style="margin:0 0 18px;color:#64748b;font-size:14px;">
    Browse products, search quickly, and customize visible columns.
</p>

<!-- COLUMN FILTER -->
<div style="position:relative;margin-bottom:15px;">
<button onclick="toggleColumns()" class="btn-small">
    <i class="fa fa-table"></i> Columns
</button>

<div id="columnDropdown">
<form method="get">

<input type="hidden" name="q" value="<?php echo e($q); ?>">

<div class="column-grid">
<?php foreach($allowed_columns as $key=>$label): ?>
<label>
<input type="checkbox" name="columns[]" value="<?php echo $key ?>"
<?php if(in_array($key,$valid_columns)) echo "checked"; ?>>
<?php echo $label ?>
</label>
<?php endforeach; ?>
</div>

<button class="btn-small" style="width:100%;margin-top:10px;">Apply Columns</button>
</form>
</div>
</div>

<!-- SEARCH -->
<form method="get" class="search-box">

<div class="search-wrapper">

<div class="search-left">
<label>Search By</label>

<input type="search" id="searchInput" name="q"
placeholder="Type category / product..."
value="<?php echo e($q); ?>">
</div>

<div class="search-right">

<button type="submit" class="search-btn">
<i class="fa fa-search"></i> Search
</button>

<div class="count-badge">
<?php echo $total; ?> products
</div>

</div>

</div>

<?php foreach($valid_columns as $col): ?>
<input type="hidden" name="columns[]" value="<?php echo $col; ?>">
<?php endforeach; ?>

</form>

<!-- TABLE -->
<table class="table">
<thead>
<tr>

<th>No.</th>

<?php foreach($valid_columns as $col): ?>
<th><?php echo $allowed_columns[$col]; ?></th>
<?php endforeach; ?>

</tr>
</thead>

<tbody>

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

<td><?php echo $i++; ?></td>

<?php foreach($valid_columns as $col): ?>
<td><?php echo e($p[$col]); ?></td>
<?php endforeach; ?>

</tr>
<?php endforeach; ?>

</tbody>
</table>

<!-- PAGINATION -->
<div class="pagination">
<?php for($i=1;$i<=$total_pages;$i++): ?>
<a href="?page=<?php echo $i; ?>&q=<?php echo urlencode($q); ?>
<?php foreach($valid_columns as $col): ?>&columns[]=<?php echo $col; ?><?php endforeach; ?>">
<?php echo $i; ?>
</a>
<?php endfor; ?>
</div>

</div>
</div>

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

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

if (searchInput) {
    searchInput.addEventListener('keyup', function () {
        clearTimeout(timer);

        const query = this.value;

        timer = setTimeout(() => {
            fetch('?ajax=1&q=' + encodeURIComponent(query))
                .then(res => res.text())
                .then(data => {
                    document.getElementById('tableBody').innerHTML = data;
                });
        }, 300);
    });
}
</script>

</body>
</html>