<?php
// register_product.php
session_start();
require_once __DIR__ . '/../config.php'; // safe include

// -- auth check
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}
$userid = (int)$_SESSION['user_id'];
$role = $_SESSION['role'] ?? '';
$is_admin = ($role === 'admin');

// helper
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 = [];

/* ---------- Handle delete (POST) ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_product'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid CSRF token.';
    } else {
        $del_id = (int)($_POST['delete_id'] ?? 0);
        if ($del_id <= 0) {
            $errors[] = 'Invalid product id.';
        } else {
            // check ownership or admin
            $stmt = $conn->prepare("SELECT user_id FROM products WHERE id = ?");
            $stmt->bind_param("i", $del_id);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) {
                if ($row['user_id'] != $userid && !$is_admin) {
                    $errors[] = 'Access denied to delete this product.';
                } else {
                    $stmt2 = $conn->prepare("DELETE FROM products WHERE id = ?");
                    $stmt2->bind_param("i", $del_id);
                    if ($stmt2->execute()) {
                        $messages[] = 'Product deleted successfully.';
                    } else {
                        $errors[] = 'Delete failed: ' . $stmt2->error;
                    }
                    $stmt2->close();
                }
            } else {
                $errors[] = 'Product not found.';
            }
            $stmt->close();
        }
    }
}

$allowed_columns = [

    /* 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 */
    '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 */
    '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 */
    '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 / Misc */
    'qty' => 'Quantity',
    'units_per_packet' => 'Units Per Packet',
    'price_per_packet' => 'Price Per Packet',
    'gst_percent' => 'GST %',
    'tax_percent' => 'Tax %',
    'country_id' => 'Country',
    'status' => 'Status',
    'created_at' => 'Created At'
];
$allowed_columns['variation_actions'] = 'Variations';
$selected_columns = $_GET['columns'] ?? [
    'product_name',
    'brand_name',
    'generic_name',
    'dossier_number',
    'qty',
'registration_number',
'variation_actions'
    
];

$valid_columns = [];

foreach ($selected_columns as $col) {
    if (isset($allowed_columns[$col])) {
        $valid_columns[] = $col;
    }
}

if (!$valid_columns) {
    $valid_columns = ['product_name'];
}

/* ---------- Filters: search + status ---------- */
$search = trim($_GET['q'] ?? '');
// For admins: optional status filter via ?status_filter=approved|pending|all
$status_filter = strtolower(trim($_GET['status_filter'] ?? ''));
$valid_statuses = ['approved','pending','rejected']; // extend if you use more

/* ---------- Build WHERE clauses ---------- */
$where = [];
$params = [];
if ($search !== '') {
    $where[] = "(p.product_name LIKE ? OR p.brand_name LIKE ? OR p.dossier_number LIKE ? OR p.generic_name LIKE ?)";
    $like = "%$search%";
    $params = array_merge($params, [$like, $like, $like, $like]);
}

// Non-admins should only see approved products
if (!$is_admin) {
    $where[] = "p.status = 'approved'";
} else {
    // admin can filter; default is show all
    if ($status_filter !== '' && in_array($status_filter, $valid_statuses, true)) {
        $where[] = "p.status = '" . $conn->real_escape_string($status_filter) . "'";
    }
}

$where_sql = '';
if (!empty($where)) {
    $where_sql = 'WHERE ' . implode(' AND ', $where);
}

/* ---------- Export CSV if requested (respects same filters) ---------- */
if (isset($_GET['export']) && $_GET['export'] == '1') {
    $sql_export = "SELECT p.id, p.product_name, p.brand_name, p.generic_name, p.dossier_number,
                         p.samples_submitted_on, p.created_at,
                         (SELECT country_name FROM countries c WHERE c.id = p.country_id LIMIT 1) AS country_name,
                         p.status
                  FROM products p
                  $where_sql
                  ORDER BY p.created_at DESC";
    $stmt_e = $conn->prepare($sql_export);
    if ($stmt_e) {
        if (!empty($params)) {
            $stmt_e->bind_param(str_repeat('s', count($params)), ...$params);
        }
        $stmt_e->execute();
        $res = $stmt_e->get_result();
    } else {
        $res = $conn->query($sql_export);
    }

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=registered_products_' . date('Ymd_His') . '.csv');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID','Product Name','Brand','Generic','Dossier','Submitted On','Country','Status','Created At']);
    if ($res) {
        while ($r = $res->fetch_assoc()) {
            fputcsv($out, [
                $r['id'],
                $r['product_name'],
                $r['brand_name'],
                $r['generic_name'],
                $r['dossier_number'],
                $r['samples_submitted_on'],
                $r['country_name'],
                $r['status'] ?? '',
                $r['created_at']
            ]);
        }
    }
    fclose($out);
    exit;
}

/* ---------- Fetch products with constructed WHERE ---------- */
$sql = "SELECT p.*, p.qty,
        (SELECT country_name FROM countries c WHERE c.id = p.country_id LIMIT 1) AS country_name
        FROM products p
        $where_sql
        ORDER BY p.created_at DESC";

$stmt = $conn->prepare($sql);
$products = [];
if ($stmt) {
    if (!empty($params)) {
        $stmt->bind_param(str_repeat('s', count($params)), ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $products = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    // fallback
    $res = $conn->query($sql);
    if ($res) $products = $res->fetch_all(MYSQLI_ASSOC);
}

/* ---------- UI below ---------- */
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Registered Products</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<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;
}

/* ===== BODY ===== */
body{
font-family:Inter,Segoe UI,Arial,sans-serif;
margin:0;
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);
}

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

/* ===== TITLE ===== */
.page-title{
font-size:24px;
font-weight:800;
margin-bottom:22px;
display:flex;
align-items:center;
gap:10px;
}

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

/* ===== TOOLBAR ===== */
.toolbar{
display:flex;
gap:12px;
flex-wrap:wrap;
align-items:center;
justify-content:space-between;
margin-bottom:22px;
}

/* ===== INPUT ===== */
input[type=text]{
padding:12px 14px;
border-radius:14px;
border:1px solid var(--border);
min-width:240px;
background:#fff;
transition:.2s;
}

input[type=text]:focus{
border-color:#000;
outline:none;
box-shadow:0 0 0 3px rgba(0,0,0,.05);
}

/* ===== SELECT ===== */
select{
padding:12px;
border-radius:14px;
border:1px solid var(--border);
background:#fff;
}

/* ===== BUTTON ===== */
.btn{
display:inline-flex;
align-items:center;
gap:6px;
padding:10px 16px;
border-radius:14px;
border:0;
background:#000;
color:#fff;
font-weight:600;
cursor:pointer;
text-decoration:none;
transition:.2s;
}

.btn:hover{
transform:translateY(-2px);
background:linear-gradient(135deg,var(--primary-dark),#2563eb);
box-shadow:0 8px 20px rgba(0,0,0,.15);
}

.btn.ghost{
background:#fff;
color:#111;
border:1px solid var(--border);
}

.btn.ghost:hover{
background:#f1f5f9;
}

/* ===== TABLE ===== */


/* HEADER */
.table th{
    background:#374155;
    color:#fff;
    padding:14px 18px;
    font-size:14px;
    text-align:left;
    white-space:nowrap;
    word-break:normal;
    min-width:180px;
}

/* rounded header */
.table th:first-child{
border-radius:12px 0 0 12px;
}
.table th:last-child{
border-radius:0 12px 12px 0;
}

/* ROW */
.table td{
background:#f9fbfd;
padding:14px;
font-size:14px;
border-top:1px solid var(--border);
border-bottom:1px solid var(--border);
}
.table td{
    white-space:normal;
    word-break:break-word;
    vertical-align:top;
    min-width:180px;
}

.table th{
    white-space:nowrap;
    word-break:normal;
}
.table th:first-child,
.table td:first-child{
    min-width:70px;
    width:70px;
}
.table-scroll{
    width:100%;
    overflow-x:auto;
    -webkit-overflow-scrolling:touch;
}

.table{
       width:max-content;
    min-width:1600px;
    border-collapse:separate;
    border-spacing:0 12px;
    table-layout:auto;
}

.table th,
.table td{
    white-space:normal;
    word-break:break-word;
    vertical-align:top;
}
/* rounded row */
.table td:first-child{
border-left:1px solid var(--border);
border-radius:12px 0 0 12px;
}
.table td:last-child{
border-right:1px solid var(--border);
border-radius:0 12px 12px 0;
}

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

/* ===== SMALL TEXT ===== */
.small{
font-size:13px;
color:var(--muted);
}

/* ===== BADGES ===== */
.badge{
padding:4px 10px;
border-radius:999px;
font-size:12px;
font-weight:600;
}

.badge.approved{
background:#dcfce7;
color:#166534;
}

.badge.pending{
background:#fef3c7;
color:#92400e;
}

/* ===== NOTICE ===== */
.notice{
padding:12px;
border-radius:10px;
margin-bottom:12px;
font-size:14px;
}

.notice.success{
background:#dcfce7;
color:#166534;
}

.notice.error{
background:#fee2e2;
color:#991b1b;
}

/* ===== ACTION BUTTON ===== */
.action-btn{
padding:6px 8px;
border-radius:8px;
transition:.2s;
}

.action-btn:hover{
background:#e2e8f0;
}

/* ===== PRODUCT NOTE ===== */
.product-note{
display:block;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
max-width:100%;
}
.page-title{
margin-bottom:18px;
padding-bottom:8px;
border-bottom:1px solid #e5e7eb;
}

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

.toolbar{
flex-direction:column;
align-items:flex-start;
}

input[type=text]{
width:100%;
}
}
/* ================= MOBILE RESPONSIVE ================= */
@media (max-width:768px){

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

    body{
        padding:65px 10px;
    }

    /* 🔥 TITLE */
    .page-title{
        font-size:18px;
        flex-direction:column;
        align-items:flex-start;
        gap:6px;
    }

    /* 🔥 TOOLBAR */
    .toolbar{
        flex-direction:column;
        align-items:stretch;
        gap:10px;
    }

    .toolbar > div{
        width:100%;
    }

    input[type=text]{
        width:100%;
    }

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

    /* 🔥 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;
        align-items:flex-start;
        padding:8px 0;
        border:none;
        font-size:13px;
        gap:10px;
    }

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

}
</style>
</head>
<body>
<?php include 'rasidebar.php'; ?>
<?php include '../header.php'; ?>
<div class="container">
  <?php foreach ($messages as $m): ?>
    <div class="notice success"><?php echo e($m); ?></div>
  <?php endforeach; ?>
  <?php foreach ($errors as $er): ?>
    <div class="notice error"><?php echo e($er); ?></div>
  <?php endforeach; ?>

  <div class="card">
    <div class="page-title">
    <i class="fa fa-box"></i> Registered Products
</div>
    <div class="toolbar">
      <div class="form-inline">
        <div style="display:flex;gap:8px;align-items:center;">
          <input id="searchInput" type="text" name="q" placeholder="Search product / brand / dossier" value="<?php echo e($search); ?>" autocomplete="off">
          <?php if ($is_admin): ?>
            <select name="status_filter" onchange="document.getElementById('searchForm').submit();">
              <option value="" <?php if($status_filter==='') echo 'selected'; ?>>All statuses</option>
              <option value="approved" <?php if($status_filter==='approved') echo 'selected'; ?>>Approved</option>
              <option value="pending" <?php if($status_filter==='pending') echo 'selected'; ?>>Pending</option>
              <option value="rejected" <?php if($status_filter==='rejected') echo 'selected'; ?>>Rejected</option>
            </select>
          <?php endif; ?>
          <i class="fa fa-search"></i> Search</button>
          <!-- Reset button removed per request -->
        </div>
      </div>
      <div style="display:flex;gap:8px;flex-wrap:wrap;">

    <!-- COLUMN FILTER -->
    <div style="position:relative;display:inline-block;">

        <button type="button" class="btn ghost" onclick="toggleColumns()">
            <i class="fa fa-table"></i> Columns
        </button>

        <div id="columnDropdown" style="display:none;position:absolute;top:48px;left:0;background:#fff;border:1px solid #ddd;border-radius:12px;padding:15px;box-shadow:0 8px 25px rgba(0,0,0,.12);width:340px;z-index:999;">

            <form method="get">

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

                <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;max-height:300px;overflow:auto;">

                    <?php foreach($allowed_columns as $key => $label): ?>
                        <label style="font-size:13px;">
                            <input type="checkbox" name="columns[]" value="<?php echo $key; ?>"
                            <?php if(in_array($key,$valid_columns)) echo 'checked'; ?>>
                            <?php echo e($label); ?>
                        </label>
                    <?php endforeach; ?>

                </div>

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

            </form>

        </div>

    </div>
        <a class="btn" href="?<?php echo http_build_query(array_merge($_GET, ['export'=>1])); ?>"><i class="fa fa-file-csv"></i> Export CSV</a>
        <a class="btn ghost" href="add_product.php" style="text-decoration:none;padding:8px 10px;"><i class="fa fa-plus"></i> Add Product</a>
      </div>
    </div>

    <div class="table-scroll"> 
    <table class="table" role="table" aria-label="Registered products">

      <thead>
        <tr>
          <th>No.</th>
<?php foreach($valid_columns as $col): ?>
    <th><?php echo e($allowed_columns[$col]); ?></th>
<?php endforeach; ?>
         
        </tr>
      </thead>
      <tbody>
        <?php if (empty($products)): ?>
          <tr><td colspan="<?php echo count($valid_columns) + 1; ?>" class="small">No products found.</td></tr>
        <?php else: ?>
          <?php $i = 1; foreach ($products as $p): ?>
            <tr>
             <td data-label="No." class="small"><?php echo $i++; ?></td>

<?php foreach($valid_columns as $col): ?>
<td data-label="<?php echo e($allowed_columns[$col]); ?>">
<?php
if ($col === 'variation_actions') {

    echo '
    <div style="display:flex;gap:6px;flex-wrap:wrap;">
        <a href="add_product.php?id='.$p['id'].'&variation=1" class="btn" style="padding:6px 10px;font-size:12px;">
            <i class="fa fa-plus"></i> Edit
        </a>

        <a href="view_variations.php?product_id='.$p['id'].'" class="btn ghost" style="padding:6px 10px;font-size:12px;">
            <i class="fa fa-eye"></i> View
        </a>
    </div>';

}
elseif ($col === 'country_id') {
    echo !empty($p['country_name']) ? e($p['country_name']) : '&mdash;';
}
else {
    echo !empty($p[$col]) ? e($p[$col]) : '&mdash;';
}
?>
</td>
<?php endforeach; ?>
       
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
</div>
  </div>
</div>
<script>
const searchInput = document.getElementById("searchInput");
const rows = document.querySelectorAll(".table tbody tr");

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

    let value = this.value.toLowerCase();

    rows.forEach(row => {

        let text = row.innerText.toLowerCase();

        row.style.display = text.includes(value) ? "" : "none";

    });

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

document.addEventListener("click", function(e){
    const box = document.getElementById("columnDropdown");
    if(!e.target.closest("#columnDropdown") && !e.target.closest("button")){
        box.style.display = "none";
    }
});
</script>
</html>