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

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

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

/* 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=?");
        $stmt->bind_param("i",$del_id);
        $stmt->execute();
        $res=$stmt->get_result();
        $row=$res->fetch_assoc();
        $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.";
        }

        $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',
    'registration_date' => 'Registration Date',
    '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 */
$selected_columns = $_GET['columns'] ?? [
'product_name','brand_name','qty','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 + FILTER */

$q = trim($_GET['q'] ?? '');
$country_filter = (int)($_GET['country_id'] ?? 0);

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

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

/* SEARCH */

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%";
$params=array_merge($params,[$like,$like,$like,$like,$like]);
$types.="sssss";
}

/* COUNTRY FILTER */

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

$where_sql="";
if($where){
$where_sql="WHERE ".implode(" AND ",$where);
}

/* TOTAL COUNT */

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

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

$stmt->execute();
$total=$stmt->get_result()->fetch_assoc()['total'];
$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.id 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=[];
while($row=$result->fetch_assoc()){
$products[]=$row;
}

$stmt->close();

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

/* COUNTRIES */

$countries=[];
$res=$conn->query("SELECT id,country_name FROM countries ORDER BY country_name");

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

<!doctype html>
<html>
<head>

<meta charset="utf-8">
<title>Manage 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:80px 25px;
    overflow-x:hidden; /* page wide nahi hoga */
}

.container{
    margin-left:260px;
    max-width:calc(100vw - 260px);
    overflow-x:hidden;
}

.card{
    background:#fff;
    border-radius:14px;
    padding:25px;
    box-shadow:0 10px 25px rgba(0,0,0,0.05);
    overflow:hidden; /* scroll card ke andar rahe */
}

/* TOP BAR */

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

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

/* FILTER */

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

.filter input{
flex:1;
padding:12px;
border-radius:8px;
border:1px solid #e2e8f0;
font-size:14px;
}

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

/* BUTTONS */

.btn{
background:#334155;
color:#fff;
padding:10px 18px;
border-radius:20px;
border:none;
cursor:pointer;
font-size:14px;
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 WRAPPER */
.table-scroll{
    width:100%;
    max-width:100%;
    overflow-x:auto;
    overflow-y:hidden;
    -webkit-overflow-scrolling:touch;
    border-radius:12px;
}

/* TABLE */
.table{
    width:max-content;   /* columns badhenge to table wide hoga */
    min-width:100%;      /* kam columns par bhi full rahe */
    border-collapse:separate;
    border-spacing:0 12px;
}

/* TABLE HEADER */
.table th{
    background:#334155;
    color:#fff;
    padding:14px;
    font-size:13px;
    text-align:left;
    min-width:160px;
    white-space:normal;
}

.table th:first-child{
    border-radius:10px 0 0 10px;
    min-width:70px;
}

.table th:last-child{
    border-radius:0 10px 10px 0;
    min-width:140px;
}

/* TABLE ROWS */
.table td{
    background:#f8fafc;
    padding:14px;
    font-size:13px;
    border-top:1px solid #e2e8f0;
    border-bottom:1px solid #e2e8f0;
    min-width:160px;
    word-break:break-word;
}

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

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

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

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

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

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

/* 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;
}

/* ================= REAL MOBILE FIX ================= */
@media (max-width:768px){

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

    body{
        padding:65px 10px;
    }

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

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

    /* ðŸ”¥ FILTER FULL FIX */
    .filter{
        flex-direction:column;
        align-items:stretch;
        gap:8px;
        padding:12px;
    }

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

    .btn-small{
        width:100%;
    }

    /* ðŸ”¥ COLUMN DROPDOWN FIX */
    #columnDropdown{
        width:100%;
        left:0;
    }

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

    /* ðŸ”¥ TABLE â†’ TRUE CARD UI */
    .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;
        align-items:center;
        padding:8px 0;
        border:none;
        font-size:13px;
    }

    .table tbody td::before{
        content:attr(data-label);
        font-weight:600;
        color:#64748b;
        flex:0 0 45%;
    }

    /* ðŸ”¥ ACTION BUTTON FIX */
    .table tbody td:last-child div{
        justify-content:flex-end;
        width:100%;
        gap:6px;
    }

    /* ðŸ”¥ 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">

<!-- TOP BAR -->

<div class="top-bar">

<h2>Manage Products</h2>


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

</div>


<!-- COLUMN SELECT -->

<div style="margin-bottom:15px; position:relative; display:inline-block;">

<button type="button" class="btn-small" 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="<?php echo $key ?>"
<?php if(in_array($key,$valid_columns)) echo "checked"; ?>>
<?php echo $label ?>
</label>

<?php endforeach; ?>

</div>

<br>

<button class="btn" style="width:100%">Apply Columns</button>

</form>

</div>

</div>


<!-- FILTER -->

<form class="filter" method="get">

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

<select name="country_id">

<option value="">All Countries</option>

<?php foreach($countries as $c): ?>

<option value="<?php echo $c['id']; ?>" <?php if($country_filter==$c['id']) echo "selected"; ?>>

<?php echo e($c['country_name']); ?>

</option>

<?php endforeach; ?>

</select>

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

</form>

<div class="table-scroll">

<table class="table">

<thead>
<tr>

<th>No.</th>

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

<th>Country</th>
<th>Registration Date</th>
<th>File</th>
<th>Actions</th>

</tr>
</thead>

<tbody>

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

<tr>

<td data-label="ID"><?php echo $i++; ?></td>

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

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

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

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

<td>
<div style="display:flex;gap:6px;flex-wrap:wrap">

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

<a class="btn-small" href="add_product.php?id=<?php echo $p['id']; ?>&variation=1" title="Add Variation">
<i class="fa fa-plus"></i>
</a>

<a class="btn-small" href="view_variations.php?product_id=<?php echo $p['id']; ?>" title="View Variations">
<i class="fa fa-code-branch"></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 type="submit" 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_id=<?php echo $country_filter; ?>">

<?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";

}

document.addEventListener("click",function(e){

var box=document.getElementById("columnDropdown");

if(!e.target.closest("#columnDropdown") && !e.target.closest("button")){
box.style.display="none";
}

});

</script>

</body>
</html>