<?php
// add_product.php  -- supports both add and edit (create + update)
session_start();
require_once '../config.php';

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

function showError($errors, $field){
    foreach($errors as $err){
        if(stripos($err, $field) !== false){
            return "<div class='field-error'>$err</div>";
        }
    }
    return "";
}
$userid = (int)($_SESSION['user_id'] ?? 0);
$role = $_SESSION['role'] ?? '';

function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }

function parse_date_or_null($val){
    $val = trim($val);
    if ($val === '') return null;
    $ts = strtotime($val);
    return $ts === false ? null : date('Y-m-d', $ts);
}

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

$errors = [];
$success = null;

/* helper to bind params by reference */
function bind_params_ref(mysqli_stmt $stmt, string $types, array $params) {
    // mysqli::bind_param requires arguments by reference
    $refs = [];
    $refs[] = &$types;
    foreach ($params as $key => $value) {
        $refs[] = &$params[$key];
    }
    return call_user_func_array([$stmt, 'bind_param'], $refs);
}

/* Form template keys */
$form = array_fill_keys([

    /* Commercial Product Info */
    'product_name','generic_name','brand_name',
    'standards','strength','volume',
    'dosage_form','indication',
    'primary_packing','secondary_packing','shelf_life',
    'manufactured_by','marketed_by','distributed_by',

    /* Samples Details */
    'samples_batch_no',
    'samples_manufacturing_date',
    'samples_expiry_date',
    'samples_submitted_on',
    'samples_coa_file',
    'samples_tracking_no',
    'samples_qty',
    'samples_sent_to',
    'samples_destination_address',

    /* WS Details */
    'ws_batch_no',
    'ws_manufacturing_date',
    'ws_expiry_date',
    'ws_submitted_on',
    'ws_coa_file',
    'ws_tracking_no',
    'ws_qty',
    'ws_sent_to',
    'ws_destination_address',

    /* Dossier Details */
    'dossier_number',
    'submitted_to',
    'dossier_sent_on',
    'query_received_on',
    'query_submitted_on',
    'dossier_submitted_in_moh_on',
    'moh_comments_received_on',
    'moh_comments',
    'moh_comments_submitted_on',

  /* Registration */
'registration_number',
'registration_details',
'purchase_name',
'registration_date',
'registration_exp_date',
'renewal_process_start',

    /* Pricing & Misc */
    'qty',
    'country_id',
    'units_per_packet',
    'price_per_packet',
    'hsn_no'   // ✅ ADD THIS    
], '');

/* Determine edit mode (GET id or hidden POST product_id) */
$edit_id = (int)($_GET['id'] ?? $_POST['product_id'] ?? 0);
$is_edit = $edit_id > 0;

/* If editing — fetch existing row to get file_path (even on POST we need existing file path) */
$existing_file = null;
if ($is_edit) {
    $stmt = $conn->prepare("SELECT * FROM products WHERE id = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("i", $edit_id);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            // populate form defaults with DB values (only for GET load)
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                foreach (array_keys($form) as $k) {
                    if (array_key_exists($k, $row)) $form[$k] = $row[$k];
                }
            }
            $existing_file = $row['file_path'] ?? null;
        } else {
            $errors[] = 'Product not found for editing.';
            $is_edit = false;
            $edit_id = 0;
        }
        $stmt->close();
    } else {
        $errors[] = 'DB error: ' . $conn->error;
        $is_edit = false;
        $edit_id = 0;
    }
}

/* Handle POST (create or update) - accept both submit names for compatibility */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['add_product']) || isset($_POST['save_product']))) {

    // CSRF
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $errors[] = 'Invalid form submission.';
    }

    // populate form from POST
    foreach ($form as $k => $v) {
        $form[$k] = trim($_POST[$k] ?? '');
    }

    // Basic validation
    if ($form['product_name'] === '') {
        $errors[] = 'Product Name is required.';
    }

    if ($form['country_id'] === '') {
        $errors[] = 'Please select a Country.';
    }

    if ($form['qty'] === '') {
        $errors[] = 'Packet Quantity is required.';
    }

    if ($form['units_per_packet'] === '') {
        $errors[] = 'Units per Packet is required.';
    }

    if ($form['price_per_packet'] === '') {
        $errors[] = 'Price per Packet is required.';
    }

    // FORMAT VALIDATION
    if ($form['qty'] !== '' && !ctype_digit((string)$form['qty'])) {
        $errors[] = 'Packet Quantity must be a valid number.';
    }

    if ($form['units_per_packet'] !== '' && !ctype_digit((string)$form['units_per_packet'])) {
        $errors[] = 'Units per Packet must be a valid number.';
    }

    if ($form['price_per_packet'] !== '' && !is_numeric($form['price_per_packet'])) {
        $errors[] = 'Price must be a valid amount.';
    }

    // get India ID from DB (only once)
    $indiaId = null;
    $res = $conn->query("SELECT id FROM countries WHERE country_name = 'India' LIMIT 1");
    if ($res && $row = $res->fetch_assoc()) {
        $indiaId = (int)$row['id'];
    }

    // convert posted country id to int
    $postCountryId = (int)($form['country_id'] ?? 0);


    // Parse date fields
   $date_keys = [
    'samples_manufacturing_date',
    'samples_expiry_date',
    'samples_submitted_on',

    'ws_manufacturing_date',
    'ws_expiry_date',
    'ws_submitted_on',

    'dossier_sent_on',
    'query_received_on',
    'query_submitted_on',
    'dossier_submitted_in_moh_on',
    'moh_comments_received_on',
    'moh_comments_submitted_on',

    'registration_date',
    'registration_exp_date',
    'renewal_process_start'
];
    foreach ($date_keys as $d) {
        if ($form[$d] !== '') {
            $parsed = parse_date_or_null($form[$d]);
            if ($parsed === null) $errors[] = "Invalid date: $d";
            else $form[$d] = $parsed;
        } else {
            $form[$d] = null;
        }
    }

    // casts
    $country_id = (int)($form['country_id'] ?? 0);
    $qty = ($form['qty'] === '') ? null : (int)$form['qty'];
    $units = ($form['units_per_packet'] === '') ? null : (int)$form['units_per_packet'];
    $price = ($form['price_per_packet'] === '') ? null : (float)$form['price_per_packet'];


    // file handling
  // file handling
$remove_file = isset($_POST['remove_file']) && $_POST['remove_file'] == '1';

if (!empty($_POST['uploaded_file'])) {
    $file_path = $_POST['uploaded_file'];
}
elseif ($remove_file) {
    if (!empty($existing_file)) {
        $old = __DIR__ . '/../' . $existing_file;
        if (file_exists($old)) @unlink($old);
    }
    $file_path = null;
}
else {
    $file_path = $existing_file ?? null;
}

    /* If no errors, do insert or update */
  if (empty($errors)) {

    $request_type = $is_edit ? 'edit' : 'add';
    $request_data = json_encode($form, JSON_UNESCAPED_UNICODE);

    if ($is_edit) {

        $stmt = $conn->prepare("INSERT INTO admin_product_approval
            (product_id, product_name, variation, type, status)
            VALUES (?, ?, ?, ?, 'pending')");

        $stmt->bind_param("isss",
            $edit_id,
            $form['product_name'],
            $request_data,
            $request_type
        );

    } else {

        $stmt = $conn->prepare("INSERT INTO admin_product_approval
            (product_id, product_name, variation, type, status)
            VALUES (NULL, ?, ?, ?, 'pending')");

        $stmt->bind_param("sss",
            $form['product_name'],
            $request_data,
            $request_type
        );
    }

    if ($stmt->execute()) {
        header("Location: manage_product.php?request_sent=1");
        exit;
    } else {
        $errors[] = $stmt->error;
    }
}
    if ($is_edit && $edit_id > 0) {

        if ($role === 'ra') {
            // RA can update only RA fields
            $sql = "UPDATE products SET
                submitted_to=?,
                dossier_number=?,
                submitted_on=?,
                samples_submitted_on=?,
                samples_batch_no_expiry=?,
                ws_batch_no=?,
                query_received_on=?,
                query_sent_on=?,
                submitted_to_fda_on=?,
                fda_query_received_on=?,
                fda_query_submitted_on=?,
                result_comments=?,
                registration_number=?,
                registration_date=?,
                registration_exp_date=?,
                renewal_process_start=?,
                qty=?,
                units_per_packet=?,
                price_per_packet=?,   // ✅ ADD THIS LINE
                hsn_no=?,
                file_path=?
                WHERE id = ?";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                $errors[] = 'Prepare failed: ' . $conn->error;
            } else {
                // 16 strings + qty(i), units(i), price(d), gst(d), tax(d), file_path(s), id(i)
            $types = str_repeat("s", 16) . "iidssi";
                $params = [
                    $form['submitted_to'],
                    $form['dossier_number'],
                    $form['submitted_on'],
                    $form['samples_submitted_on'],
                    $form['samples_batch_no_expiry'],
                    $form['ws_batch_no'],
                    $form['query_received_on'],
                    $form['query_sent_on'],
                    $form['submitted_to_fda_on'],
                    $form['fda_query_received_on'],
                    $form['fda_query_submitted_on'],
                    $form['result_comments'],
                    $form['registration_number'],
                    $form['registration_date'],
                    $form['registration_exp_date'],
                    $form['renewal_process_start'],
                    $qty,
                    $units,
                    $price,
                    $form['hsn_no'],   // ✅ ADD THIS
                    $file_path,
                    $edit_id
                ];

                if (!bind_params_ref($stmt, $types, $params)) {
                    $errors[] = 'Bind failed (update).';
                } else {
                    if ($stmt->execute()) {
                        header('Location: manage_product.php?updated=1');
                        exit;
                    } else {
                        $errors[] = 'Execute failed: ' . $stmt->error;
                    }
                }
                $stmt->close();
            }

        } else {
            // ADMIN can update all fields
            $sql = "UPDATE products SET
                product_name=?, generic_name=?, brand_name=?,
                standards=?, strength=?, volume=?,
                dosage_form=?, indication=?,
                primary_packing=?, secondary_packing=?, shelf_life=?,
                manufactured_by=?, marketed_by=?, distributed_by=?,
                dossier_number=?, submitted_to=?,
                submitted_on=?, samples_submitted_on=?, samples_batch_no_expiry=?,
                ws_batch_no=?,
                query_received_on=?, query_sent_on=?,
                submitted_to_fda_on=?, fda_query_received_on=?, fda_query_submitted_on=?,
                result_comments=?,
                registration_number=?, registration_date=?, registration_exp_date=?, renewal_process_start=?,
                qty=?, units_per_packet=?, price_per_packet=?, hsn_no=?, country_id=?, file_path=?
                WHERE id = ?";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                $errors[] = 'Prepare failed: ' . $conn->error;
            } else {
                // 29 strings + qty(i), units(i), price(d), gst(d), tax(d), country_id(i), file_path(s), id(i)
                $types = str_repeat("s", 29) . "iidsisi";

                $params = [
                    $form['product_name'],
                    $form['generic_name'],
                    $form['brand_name'],
                    $form['standards'],
                    $form['strength'],
                    $form['volume'],
                    $form['dosage_form'],
                    $form['indication'],
                    $form['primary_packing'],
                    $form['secondary_packing'],
                    $form['shelf_life'],
                    $form['manufactured_by'],
                    $form['marketed_by'],
                    $form['dossier_number'],
                    $form['submitted_to'],
                    $form['submitted_on'],
                    $form['samples_submitted_on'],
                    $form['samples_batch_no_expiry'],
                    $form['ws_batch_no'],
                    $form['query_received_on'],
                    $form['query_sent_on'],
                    $form['submitted_to_fda_on'],
                    $form['fda_query_received_on'],
                    $form['fda_query_submitted_on'],
                    $form['result_comments'],
                    $form['registration_number'],
                    $form['registration_date'],
                    $form['registration_exp_date'],
                    $form['renewal_process_start'],
                    $qty,
                    $units,
                    $price,
                    $form['hsn_no'],   // ✅ ADD
                    $country_id,
                    $file_path,
                    $edit_id
                ];

                if (!bind_params_ref($stmt, $types, $params)) {
                    $errors[] = 'Bind failed (update).';
                } else {
                    if ($stmt->execute()) {
                        header('Location: manage_product.php?updated=1');
                        exit;
                    } else {
                        $errors[] = 'Execute failed: ' . $stmt->error;
                    }
                }
                $stmt->close();
            }
        }

    } else {
        /* ---------- INSERT (fixed) ---------- */
        $sql = "INSERT INTO products (
            product_name, generic_name, brand_name,
            standards, strength, volume,
            dosage_form, indication,
            primary_packing, secondary_packing, shelf_life,
            manufactured_by, marketed_by, distributed_by,
            dossier_number, submitted_to,
            submitted_on, samples_submitted_on, samples_batch_no_expiry,
            ws_batch_no,
            query_received_on, query_sent_on,
            submitted_to_fda_on, fda_query_received_on, fda_query_submitted_on,
            result_comments,
            registration_number, registration_date, registration_exp_date, renewal_process_start,
            country_id,
            file_path,
            created_by,
            user_id,
            qty,
            units_per_packet,
            price_per_packet,
            hsn_no
        ) VALUES (
            ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
        )";

        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            $errors[] = 'Prepare failed: ' . $conn->error;
        } else {
            $types = str_repeat("s", 29) . "isiiids";

            $params = [
                $form['product_name'],
                $form['generic_name'],
                $form['brand_name'],
                $form['standards'],
                $form['strength'],
                $form['volume'],
                $form['dosage_form'],
                $form['indication'],
                $form['primary_packing'],
                $form['secondary_packing'],
                $form['shelf_life'],
                $form['manufactured_by'],
                $form['marketed_by'],
                $form['dossier_number'],
                $form['submitted_to'],
                $form['submitted_on'],
                $form['samples_submitted_on'],
                $form['samples_batch_no_expiry'],
                $form['ws_batch_no'],
                $form['query_received_on'],
                $form['query_sent_on'],
                $form['submitted_to_fda_on'],
                $form['fda_query_received_on'],
                $form['fda_query_submitted_on'],
                $form['result_comments'],
                $form['registration_number'],
                $form['registration_date'],
                $form['registration_exp_date'],
                $form['renewal_process_start'],
                $country_id,
                $file_path,
                $userid,
                $userid,
                $qty,
                $units,
                $price,
                $form['hsn_no']   // ✅ ADD
            ];

            if (!bind_params_ref($stmt, $types, $params)) {
                $errors[] = 'Bind failed (insert).';
            } else {
                if ($stmt->execute()) {
                    header("Location: manage_product.php?added=1");
                    exit;
                } else {
                    $errors[] = 'Execute failed: ' . $stmt->error;
                }
            }
            $stmt->close();
        }
    }
// end no errors
} // END POST BLOCK

/* Load countries for select */
$countries = [];
$res = $conn->query("SELECT id,country_name FROM countries ORDER BY country_name");
if ($res) {
    while ($r = $res->fetch_assoc()) $countries[] = $r;
} else {
    die("Countries query failed: " . $conn->error);
}

/* Render form */
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?php echo $is_edit ? 'Edit' : 'Add'; ?> Commercial Product</title>
<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;
    --soft:#f8fafc;
    --success:#dcfce7;
    --danger:#fee2e2;
}

*{
    box-sizing:border-box;
}

body{
    margin:0;
    font-family:Inter,Segoe UI,Arial,sans-serif;
    color:#000;
    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);
    min-height:100vh;
    padding:90px 24px 32px;
}

.container{
    max-width:1500px;
    margin:0 auto;
}

.main-content{
    margin-left:260px;
    min-height:100vh;
}

.content-card{
    margin-left:260px;
    background:rgba(255,255,255,.92);
    backdrop-filter:blur(8px);
    border:1px solid rgba(229,231,235,.9);
    border-radius:24px;
    box-shadow:0 18px 50px rgba(15,23,42,.10);
    padding:28px;
}

h1{
    font-size:28px;
    margin:0;
    letter-spacing:-.02em;
}

.section{
    margin-top:22px;
    padding:22px;
    border:1px solid #eef2f7;
    border-radius:20px;
    background:linear-gradient(180deg, #fff, #fbfdff);
    box-shadow:0 8px 24px rgba(15,23,42,.04);
}

.section h3{
    font-size:18px;
    margin:0 0 16px;
    color:#000;
    display:flex;
    align-items:center;
    gap:10px;
}

.section h3::before{
    content:"";
    width:10px;
    height:10px;
    border-radius:999px;
    background:#000;
    box-shadow:0 0 0 5px rgba(37,99,235,.12);
}

label{
    display:block;
    margin:14px 0 8px;
    font-weight:700;
    font-size:13px;
    color:#334155;
}

input,
select,
textarea{
    width:100%;
    padding:13px 14px;
    border:1px solid var(--border);
    border-radius:14px;
    font-size:14px;
    background:#fff;
    color:#000;
    transition:.18s ease;
    outline:none;
}

input::placeholder,
textarea::placeholder{
    color:#94a3b8;
}

input:focus,
select:focus,
textarea:focus{
    border-color:#000;
  
}

textarea{
    resize:vertical;
    min-height:110px;
}

.grid{
    display:grid;
    grid-template-columns:repeat(2, minmax(0, 1fr));
    gap:18px;
}

.grid-3{
    display:grid;
    grid-template-columns:repeat(3, minmax(0, 1fr));
    gap:18px;
}
.grid + .actions{
    grid-column: 1 / -1;
}
.card{
    background:var(--card);
    border-radius:24px;
    border:1px solid #eef2f7;
    box-shadow:0 12px 30px rgba(15,23,42,.06);
    padding:24px;
}

.card h2{
    font-size:22px;
    margin:0 0 18px;
    letter-spacing:-.02em;
}

.actions{
    margin-top:28px;
    display:flex;
    align-items:center;
    gap:14px;
    flex-wrap:wrap;
}

.actions-center{
    justify-content:center;
}

.btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:10px;
    background:#000;
    color:#fff;
    border:none;
    padding:12px 20px;
    font-size:14px;
    font-weight:700;
    border-radius:14px;
    cursor:pointer;
    box-shadow:0 10px 20px rgba(37,99,235,.18);
    transition:.18s ease;
    text-decoration:none;
    min-width:150px;
}

.btn:hover{
    transform:translateY(-1px);
    background:linear-gradient(135deg, var(--primary-dark), #2563eb);
}

.btn-secondary{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:10px;
    padding:12px 20px;
    border-radius:14px;
    border:1px solid var(--border);
    background:#fff;
    color:#0f172a;
    text-decoration:none;
    font-weight:700;
    min-width:150px;
    transition:.18s ease;
}

.btn-secondary:hover{
    background:#f8fafc;
    border-color:#dbe2ea;
}

.error{
    background:var(--danger);
    color:#991b1b;
    padding:14px 16px;
    border-radius:14px;
    margin-bottom:16px;
    font-weight:600;
    line-height:1.6;
    border:1px solid #fecaca;
}

.success{
    background:var(--success);
    color:#166534;
    padding:14px 16px;
    border-radius:14px;
    margin-bottom:16px;
    font-weight:600;
    border:1px solid #bbf7d0;
}

.small{
    font-size:12px;
    color:var(--muted);
    margin-top:6px;
}

.field-error{
    color:#dc2626;
    font-size:12px;
    margin-top:6px;
    font-weight:600;
}

input.error-border,
select.error-border,
textarea.error-border{
    border-color:#dc2626;
    box-shadow:0 0 0 4px rgba(220,38,38,.08);
}

.country-wrapper{
    position:relative;
    margin-top:6px;
}

.country-display{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    cursor:pointer;
}

.country-dropdown{
    position:absolute;
    top:110%;
    left:0;
    right:0;
    background:#fff;
    border:1px solid var(--border);
    border-radius:16px;
    box-shadow:0 18px 40px rgba(15,23,42,.12);
    display:none;
    z-index:999;
    padding:12px;
}

.country-list{
    max-height:240px;
    overflow:auto;
    margin-top:10px;
}

.country-item{
    display:flex;
    align-items:center;
    gap:12px;
    padding:10px;
    border-radius:12px;
    cursor:pointer;
    transition:.15s ease;
}

.country-item:hover{
    background:#f1f5f9;
}

.country-flag{
    width:28px;
    height:18px;
    border-radius:4px;
    object-fit:cover;
    flex:0 0 auto;
}
/* LABEL */
.field-label{
    font-size:14px;
    font-weight:700;
    margin-bottom:6px;
    display:block;
    color:#000;
}

/* MODERN DROPDOWN */
.modern-dropdown{
    width:100%;
    padding:12px 14px;
    border-radius:12px;
    border:1px solid #2d3748;
    background:#fff;
    color:#000;
    display:flex;
    align-items:center;
    justify-content:space-between;
    cursor:pointer;
    transition:0.2s;
}

/* HOVER */
.modern-dropdown:hover{
    border-color:#3b82f6;
}

/* FOCUS EFFECT */
.modern-dropdown:focus{
    outline:none;
    box-shadow:0 0 0 3px rgba(59,130,246,0.3);
}

/* TEXT STYLE */
#countryDisplayText{
    display:flex;
    align-items:center;
    gap:8px;
    font-size:14px;
}

/* DROPDOWN BOX */
.country-dropdown{
    border-radius:14px;
    border:1px solid #1f2937;
    background:#fff;
}

/* COUNTRY ITEM */
.country-item{
    color:#000;
}

.country-item:hover{
    background:#fff;
}

@media (max-width: 1200px){
    .content-card{
        margin-left:220px;
    }
    .main-content{
        margin-left:220px;
    }
}

@media (max-width: 992px){
    body{
        padding:84px 16px 20px;
    }

    .main-content,
    .content-card{
        margin-left:0 !important;
    }

    .grid,
    .grid-3{
        grid-template-columns:1fr;
    }
}

@media (max-width: 640px){
    .content-card{
        padding:18px;
        border-radius:18px;
    }

    h1{
        font-size:22px;
    }

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

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

    .btn,
    .btn-secondary{
        width:100%;
    }
}
.actions{
    width:100%;
    display:flex;
    justify-content:center;
    margin-top:30px;
} 

</style>
</head>
<body>
<div class="container">
  <?php if (file_exists('rasidebar.php')) include 'rasidebar.php'; ?>
  <?php if (file_exists('../header.php')) include '../header.php'; ?>

  <div class="card content-card">
    <h1><?php echo $is_edit ? 'Edit Product' : 'Add Product'; ?></h1>

    <?php if (!empty($errors)): ?>
      <div class="error">
        <?php echo implode("<br>", array_map('htmlspecialchars', $errors)); ?>
      </div>
    <?php endif; ?>

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


    <form method="post" enctype="multipart/form-data" novalidate>
      <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
      <?php if ($is_edit): ?><input type="hidden" name="product_id" value="<?php echo (int)$edit_id; ?>"><?php endif; ?>

      <!-- Product Info -->
      <div class="section">
        <h3>Product/dossier</h3>

        <label>Product Name *</label>
<input name="product_name"
value="<?php echo e($form['product_name']); ?>"
<?php if($role=='ra') echo 'readonly'; ?>
class="<?php echo ($form['product_name']=='' && !empty($errors)) ? 'error-border' : ''; ?>">

<?php echo showError($errors, 'Product Name'); ?>

        <div class="grid">
          <div>
            <label>Generic Name</label>
            <input name="generic_name" value="<?php echo e($form['generic_name']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
          </div>

          <div>
            <label>Brand Name</label>
            <input name="brand_name" value="<?php echo e($form['brand_name']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
          </div>
        </div>

       <div class="grid">
        <div>
       <label>Manufactured By</label>
       <input name="manufactured_by" value="<?php echo e($form['manufactured_by']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
        </div>

  <div>
    <label>Marketed By</label>
    <input name="marketed_by" value="<?php echo e($form['marketed_by']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
    
  </div>
  
</div>

        <div class="grid">
          <div>
            <label>Standards</label>
            <input name="standards" value="<?php echo e($form['standards']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
          </div>

          <div>
            <label>Strength</label>
            <input name="strength" value="<?php echo e($form['strength']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
          </div>
        </div>

        <div class="grid">
          <div>
            <label>Volume</label>
            <input name="volume" value="<?php echo e($form['volume']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
          </div>

          <div>
            <label>Dosage Form</label>
            <input name="dosage_form" value="<?php echo e($form['dosage_form']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
          </div>
        </div>

       <div class="grid">
  <div>
    <label>Sample Batch No</label>
    <input name="ws_batch_no" value="<?php echo e($form['ws_batch_no']); ?>">
  </div>

  <div>
    <label>Distributed By</label>
    <input name="distributed_by"
    value="<?php echo e($form['distributed_by'] ?? ''); ?>"
    <?php if($role=='ra') echo 'readonly'; ?>>
  </div>
</div>

        <label>Indication</label>
        <input name="indication" value="<?php echo e($form['indication']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
      </div>

      <!-- Packing -->
      <div class="section">
        <h3>Packing & Shelf-life</h3>
        <div class="grid">
          <div>
            <label>Primary Packing</label>
            <input name="primary_packing" value="<?php echo e($form['primary_packing']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>
          </div>
          <div>
            <label>Secondary Packing</label>
            <input name="secondary_packing" value="<?php echo e($form['secondary_packing']); ?>">
          </div>
        </div>
        <label>Shelf Life</label>
        <input name="shelf_life" value="<?php echo e($form['shelf_life']); ?>" placeholder="e.g. 24 months">
      </div>

      <!-- Regulatory Submission -->
      <div class="section">
        <h3>Regulatory Submission</h3>
        <div class="grid">
          <div>
            <label>Submitted To</label>
            <input name="submitted_to" value="<?php echo e($form['submitted_to']); ?>">
          </div>
          <div>
            <label>Dossier Number</label>
            <input name="dossier_number" value="<?php echo e($form['dossier_number']); ?>">
          </div>
        </div>

        <div class="grid-3">
          <div>
            <label>Submitted On</label>
            <input type="date" name="submitted_on" value="<?php echo e($form['submitted_on']); ?>">
          </div>
          <div>
            <label>Samples Submitted On</label>
            <input type="date" name="samples_submitted_on" value="<?php echo e($form['samples_submitted_on']); ?>">
          </div>
          <div>
            
          </div>
        </div>

        <div class="grid-3">
          <div>
            <label>Query Received On</label>
            <input type="date" name="query_received_on" value="<?php echo e($form['query_received_on']); ?>">
          </div>
          <div>
            <label>Query Sent On</label>
            <input type="date" name="query_sent_on" value="<?php echo e($form['query_sent_on']); ?>">
          </div>
          <div>
            <label>Submitted to FDA On</label>
            <input type="date" name="submitted_to_fda_on" value="<?php echo e($form['submitted_to_fda_on']); ?>">
          </div>
        </div>

        <div class="grid-3">
          <div>
            <label>FDA Query Received On</label>
            <input type="date" name="fda_query_received_on" value="<?php echo e($form['fda_query_received_on']); ?>">
          </div>
          <div>
            <label>FDA Query Submitted On</label>
            <input type="date" name="fda_query_submitted_on" value="<?php echo e($form['fda_query_submitted_on']); ?>">
          </div>
          <div>
            <label>Registration Number</label>
            <input name="registration_number" value="<?php echo e($form['registration_number']); ?>">
          </div>
        </div>
      </div>
      
      <!-- Samples Details -->
<div class="section">
  <h3>Samples Details</h3>
  <div class="grid-3">
    <div><label>Batch No</label><input name="samples_batch_no" value="<?php echo e($form['samples_batch_no']); ?>"></div>
    <div><label>Manufacturing Date</label><input type="date" name="samples_manufacturing_date" value="<?php echo e($form['samples_manufacturing_date']); ?>"></div>
    <div><label>Expiry Date</label><input type="date" name="samples_expiry_date" value="<?php echo e($form['samples_expiry_date']); ?>"></div>
  </div>
  <div class="grid-3">
    <div><label>Submitted On</label><input type="date" name="samples_submitted_on" value="<?php echo e($form['samples_submitted_on']); ?>"></div>
    <div><label>Tracking No</label><input name="samples_tracking_no" value="<?php echo e($form['samples_tracking_no']); ?>"></div>
  </div>
  <div class="grid-3">
    <div><label>Qty</label><input type="number" name="samples_qty" value="<?php echo e($form['samples_qty']); ?>"></div>
    <div><label>Sent To</label><input name="samples_sent_to" value="<?php echo e($form['samples_sent_to']); ?>"></div>
    <div><label>Destination Address</label><input name="samples_destination_address" value="<?php echo e($form['samples_destination_address']); ?>"></div>
  </div>
</div>

<!-- WS -->
<div class="section">
  <h3>WS</h3>
  <div class="grid-3">
    <div><label>Batch No</label><input name="ws_batch_no" value="<?php echo e($form['ws_batch_no']); ?>"></div>
    <div><label>Manufacturing Date</label><input type="date" name="ws_manufacturing_date" value="<?php echo e($form['ws_manufacturing_date']); ?>"></div>
    <div><label>Expiry Date</label><input type="date" name="ws_expiry_date" value="<?php echo e($form['ws_expiry_date']); ?>"></div>
  </div>
  <div class="grid-3">
    <div><label>Submitted On</label><input type="date" name="ws_submitted_on" value="<?php echo e($form['ws_submitted_on']); ?>"></div>
    <div><label>Tracking No</label><input name="ws_tracking_no" value="<?php echo e($form['ws_tracking_no']); ?>"></div>
  </div>
  <div class="grid-3">
    <div><label>Qty</label><input type="number" name="ws_qty" value="<?php echo e($form['ws_qty']); ?>"></div>
    <div><label>Sent To</label><input name="ws_sent_to" value="<?php echo e($form['ws_sent_to']); ?>"></div>
    <div><label>Destination Address</label><input name="ws_destination_address" value="<?php echo e($form['ws_destination_address']); ?>"></div>
  </div>
</div>

<!-- Dossier Details -->
<div class="section">
  <h3>Dossier Details</h3>
  <div class="grid-3">
    <div><label>Dossier Sent On</label><input type="date" name="dossier_sent_on" value="<?php echo e($form['dossier_sent_on']); ?>"></div>
    <div><label>Query Recieved On</label><input type="date" name="query_received_on" value="<?php echo e($form['query_received_on']); ?>"></div>
    <div><label>Query Submitted On</label><input type="date" name="query_submitted_on" value="<?php echo e($form['query_submitted_on']); ?>"></div>
  </div>
  <div class="grid-3">
    <div><label>Dossier Submitted in MOH On</label><input type="date" name="dossier_submitted_in_moh_on" value="<?php echo e($form['dossier_submitted_in_moh_on']); ?>"></div>
    <div><label>MOH Comments Recieved On</label><input type="date" name="moh_comments_received_on" value="<?php echo e($form['moh_comments_received_on']); ?>"></div>
    <div><label>MOH Comments Submitted On</label><input type="date" name="moh_comments_submitted_on" value="<?php echo e($form['moh_comments_submitted_on']); ?>"></div>
  </div>
  <label>Comments</label>
  <textarea name="moh_comments"><?php echo e($form['moh_comments']); ?></textarea>
</div>

      <!-- Registration -->
      <div class="section">
        <h3>Registration</h3>
     <div class="grid">
  <div>
    <label>Registration Details</label>
    <input name="registration_details" value="<?php echo e($form['registration_details']); ?>">
  </div>
  <div>
    <label>Purchase Name</label>
    <input name="purchase_name" value="<?php echo e($form['purchase_name']); ?>">
  </div>
</div>

<div class="grid">
  <div>
    <label>Registration Date</label>
    <input type="date" name="registration_date" value="<?php echo e($form['registration_date']); ?>">
  </div>
  <div>
    <label>Registration Expire Date</label>
    <input type="date" name="registration_exp_date" value="<?php echo e($form['registration_exp_date']); ?>">
  </div>
</div>

<div class="grid">
  <div>
    <label>Renewal Process Start</label>
    <input type="date" name="renewal_process_start" value="<?php echo e($form['renewal_process_start']); ?>">
  </div>
</div>

<div class="grid">
  
  <div>
    <label>Variation Submitted</label>
    <input type="date" name="variation_submitted" value="<?php echo e($form['variation_submitted']); ?>">
  </div>
  <div>
  <label>Variation Approval Date</label>
  <input type="date" name="variation_approval_date" value="<?php echo e($form['variation_approval_date']); ?>">
</div>
</div>



      <!-- Misc -->
      <div class="section">
        <h3>Misc & Uploads</h3>
        <div class="grid">
          <div>
          <label class="field-label">🌍 Country </label>

<input type="hidden" name="country_id" id="countryInput" value="<?php echo e($form['country_id']); ?>"<?php if($role=='ra') echo 'readonly'; ?>>

<div class="country-wrapper">

<button type="button"
class="country-display modern-dropdown"  <?php echo ($form['country_id']=='' && !empty($errors)) ? 'error-border' : ''; ?>"
id="countryDisplay">

<span id="countryDisplayText">
<?php 
$selectedCountry = 'Select country';
foreach($countries as $c){
    if($c['id'] == $form['country_id']){
        $selectedCountry = $c['country_name'];
        break;
    }
}
echo e($selectedCountry);
?>
</span>

<i class="fa-solid fa-chevron-down"></i>

</button>

<?php echo showError($errors, 'Country'); ?>

<div class="country-dropdown" id="countryDropdown">

<input type="text" class="input" id="countrySearch" placeholder="Search country">

<div class="country-list" id="countryList">

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

<div class="country-item"
data-id="<?php echo $c['id']; ?>"
data-name="<?php echo e($c['country_name']); ?>">

<img class="country-flag"
src="https://flagcdn.com/24x18/<?php echo strtolower(substr($c['country_name'],0,2)); ?>.png">

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

</div>

<?php endforeach; ?>

</div>
</div>
</div>
</div>
          </div>
          <div>
            <label>Packet Quantity *</label>
<input name="qty" type="number"
       value="<?php echo e($form['qty']); ?>"
       class="<?php echo ($form['qty']=='' && !empty($errors)) ? 'error-border' : ''; ?>">

<?php echo showError($errors, 'Packet Quantity'); ?>
          </div>
           <div>
    <label>HSN No.</label>
    <input name="hsn_no" type="text"
           value="<?php echo e($form['hsn_no'] ?? ''); ?>">
  </div>
        </div>

        <div class="grid" style="margin-top:12px;">
          <div>
   <label>Units per Packet *</label>
<input name="units_per_packet" type="number"
       value="<?php echo e($form['units_per_packet']); ?>"
       class="<?php echo ($form['units_per_packet']=='' && !empty($errors)) ? 'error-border' : ''; ?>">

<?php echo showError($errors, 'Units per Packet'); ?>

  <div>
    <label>Price per Packet (₹) *</label>
<input name="price_per_packet" type="number" step="0.01"
       value="<?php echo e($form['price_per_packet']); ?>"
       class="<?php echo ($form['price_per_packet']=='' && !empty($errors)) ? 'error-border' : ''; ?>">

<?php echo showError($errors, 'Price'); ?>
  </div>
  
          <div>
            <label>Upload Document (optional)</label>
           <input type="file" name="product_file" id="fileInput" accept=".pdf,.xls,.xlsx,.zip,image/*">
<input type="hidden" name="uploaded_file" id="uploaded_file">
<div class="small">Allowed: PDF, XLS/XLSX, ZIP, JPG, PNG.</div>
            <?php if (!empty($existing_file)): ?>
              <div class="file-info">
                Current file:
                <a href="../<?php echo e($existing_file); ?>" target="_blank"><?php echo basename($existing_file); ?></a>
                &nbsp;&nbsp;
                <label style="font-weight:600"><input type="checkbox" name="remove_file" value="1"> Remove file</label>
              </div>
            <?php endif; ?>
          </div>
        </div>
       
      </div>

     <!-- ✅ BUTTON HERE -->
<div class="actions actions-center">
    <button class="btn" type="submit" name="add_product" id="saveBtn">
        <?php echo $is_edit ? 'Save Changes' : 'Save Product'; ?>
    </button>

    <a class="btn-secondary" href="manage_product.php">
        Back to list
    </a>
</div>
    </form>
  </div>
</div>
<script>

const display = document.getElementById("countryDisplay");
const dropdown = document.getElementById("countryDropdown");
const search = document.getElementById("countrySearch");
const input = document.getElementById("countryInput");
const displayText = document.getElementById("countryDisplayText");

// OPEN / CLOSE DROPDOWN
display.onclick = () => {
    dropdown.style.display =
    dropdown.style.display === "block" ? "none" : "block";
};

// SEARCH FILTER
search.onkeyup = () => {
    let q = search.value.toLowerCase();

    document.querySelectorAll(".country-item").forEach(item => {
        let name = item.dataset.name.toLowerCase();
        item.style.display = name.includes(q) ? "flex" : "none";
    });
};



// COUNTRY SELECT (MAIN FIX 🔥)
document.querySelectorAll(".country-item").forEach(item => {
  item.onclick = () => {

    // set country id
    document.getElementById("countryInput").value = item.dataset.id;

    // show name + flag
    document.getElementById("countryDisplayText").innerHTML =
      `<img class="country-flag" src="${item.querySelector("img").src}"> ${item.dataset.name}`;

    // close dropdown
    document.getElementById("countryDropdown").style.display = "none";

    
    console.log("Selected:", item.dataset.id); // debug
  };
});

// CLOSE DROPDOWN WHEN CLICK OUTSIDE
document.addEventListener("click", function(e){
    if(!document.querySelector(".country-wrapper").contains(e.target)){
        dropdown.style.display = "none";
    }
});

// PAGE LOAD (for edit mode)
window.onload = function(){
    let currentText = displayText.innerText;
    if(currentText){
    }
};
if ("<?php echo $role; ?>" === "ra") {
    document.getElementById("countryDisplay").style.pointerEvents = "none";
    document.getElementById("countryDisplay").style.opacity = "0.6";
}
</script>
<script>

document.querySelector("form").addEventListener("submit", function(e){

    let valid = true;

    document.querySelectorAll("[name='product_name'], [name='price_per_packet'], [name='units_per_packet'], [name='qty']")
    .forEach(field => {

        if(field.value.trim() === ""){
            field.classList.add("error-border");
            valid = false;
        }

    });

    if(!valid){
        e.preventDefault();
    }

});

</script>
<script>

async function uploadFile(file){

    if(!file){
        alert("Please select file ❌");
        return;
    }

    const chunkSize = 5 * 1024 * 1024; // 5MB
    let start = 0;
    let index = 0;

    // disable save button while uploading
    document.getElementById("saveBtn").disabled = true;

    try {

        while(start < file.size){

            let chunk = file.slice(start, start + chunkSize);

            let formData = new FormData();
            formData.append("chunk", chunk);
            formData.append("index", index);
            formData.append("name", file.name);

            let res = await fetch("upload_chunk.php", {
                method: "POST",
                body: formData
            });

            if(!res.ok){
                throw new Error("Chunk upload failed");
            }

            start += chunkSize;
            index++;

            // optional progress
            let percent = Math.floor((start / file.size) * 100);
            console.log("Uploading:", percent + "%");
        }

        // merge
        let mergeData = new FormData();
        mergeData.append("name", file.name);
        mergeData.append("total", index);

        let mergeRes = await fetch("merge.php", {
            method: "POST",
            body: mergeData
        });

        if(!mergeRes.ok){
            throw new Error("Merge failed");
        }

        // save path
        document.getElementById("uploaded_file").value = "uploads/products/" + file.name;

        alert("Upload Complete ✅ Now click Save");

      

    } catch (err) {
        alert("Upload failed ❌ " + err.message);
        console.error(err);
    }
}

// file select trigger
document.getElementById("fileInput")
.addEventListener("change", function(){
    uploadFile(this.files[0]);
});

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