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

ini_set('display_errors',1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id']) || 
   !in_array($_SESSION['role'], ['ra','admin'])) {
    header('Location: ../login.php');
    exit;
}

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

$msg = "";
$id = (int)($_GET['id'] ?? 0);

/* ================= FETCH COUNTRIES ================= */
$countries = [];
$res = $conn->query("SELECT country_name FROM countries ORDER BY country_name ASC");
while ($row = $res->fetch_assoc()) {
    $countries[] = $row;
}
$doctors = [];
$res = $conn->query("SELECT id, name FROM doctors ORDER BY name ASC");
while ($row = $res->fetch_assoc()) {
    $doctors[] = $row;
}
/* ================= DEFAULT VALUES ================= */
$data = [
'product_name'=>'',
'generic_name'=>'',
'brand_name'=>'',
'packing'=>'',
'batch_no'=>'',
'manufacturing_date'=>'',
'expiry_date'=>'',
'manufactured_by'=>'',
'received_on'=>'',
'received_by'=>'',
'received_qty'=>'',
'sent_on'=>'',
'sent_by'=>'',
'sent_to'=>'',
'sent_qty'=>'',
'remaining_qty'=>'',
'tracking_number'=>'',
'comments'=>'',  // ✅ ADD THIS
];
/* ================= EDIT MODE ================= */
if($id){
    $res = $conn->query("SELECT * FROM sample_products WHERE id=$id");
    if($res && $res->num_rows){
        $data = $res->fetch_assoc();
    }
}

/* ================= SAVE ================= */
if (isset($_POST['submit'])) {

$product_name = trim($_POST['product_name']);
$brand_name = trim($_POST['brand_name']);
$packing = trim($_POST['packing']);
$batch_no = trim($_POST['batch_no']);
$manufacturing_date = $_POST['manufacturing_date'];
$expiry_date = $_POST['expiry_date'];
$manufactured_by = trim($_POST['manufactured_by']);
$received_on = $_POST['received_on'];
$received_by = trim($_POST['received_by']);
$received_qty = (int)$_POST['received_qty'];
$sent_on = $_POST['sent_on'];
$sent_by = trim($_POST['sent_by']);
$sent_to = trim($_POST['sent_to']);
$sent_qty = (int)$_POST['sent_qty'];
$remaining_qty = (int)$_POST['remaining_qty'];
$tracking_number = trim($_POST['tracking_number']);
$comments = trim($_POST['comments']);

    /* FILE UPLOAD */
    $file_name = $data['document'] ?? '';

    if (!empty($_FILES['document']['name'])) {

        $target_dir = "../uploads/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        $file_name = time().'_'.$_FILES['document']['name'];

        move_uploaded_file(
            $_FILES['document']['tmp_name'],
            $target_dir.$file_name
        );
    }

if($id){

$stmt = $conn->prepare("UPDATE sample_products SET
product_name=?, brand_name=?, packing=?, batch_no=?, manufacturing_date=?, expiry_date=?, manufactured_by=?, received_on=?, received_by=?, received_qty=?, sent_on=?, sent_by=?, sent_to=?, sent_qty=?, remaining_qty=?, tracking_number=?, comments=?, document=?
WHERE id=?");

$stmt->bind_param("ssssssssssississssi",
    $product_name,
    $brand_name,
    $packing,
    $batch_no,
    $manufacturing_date,
    $expiry_date,
    $manufactured_by,
    $received_on,
    $received_by,
    $received_qty,
    $sent_on,
    $sent_by,
    $sent_to,
    $sent_qty,
    $remaining_qty,
    $tracking_number,
    $comments,
    $file_name,
    $id
);
}
else {
      
    }

    if($stmt->execute()){
        header("Location: manage-sample-product.php");
        exit;
    } else {
        $msg = "Error: ".$stmt->error;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample Product</title>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/flag-icons/css/flag-icons.min.css" rel="stylesheet" />

<style>
:root{
    --primary:#2563eb;
    --primary-dark:#1d4ed8;
    --bg:#eef4ff;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#64748b;
    --border:#dbe3f0;
    --soft:#f8fbff;
    --shadow:0 20px 60px rgba(15,23,42,.10);
}

/* ===== BASE ===== */
*{
    box-sizing:border-box;
}

body{
        margin:0;
    overflow-x:hidden;
    font-family:Inter,Segoe UI,Arial,sans-serif;
    color:var(--text);
    background:
        radial-gradient(circle at top left, rgba(37,99,235,.10), transparent 24%),
        radial-gradient(circle at top right, rgba(15,23,42,.06), transparent 22%),
        linear-gradient(180deg,#f8fbff 0%, #eef4ff 100%);
    padding:28px 18px 18px;
}

a{
    color:inherit;
    text-decoration:none;
}

/* ===== LAYOUT ===== */
.main-content{
    margin-left:260px;
}

.container{
    width:100%;
overflow:hidden;
    max-width:1200px;
    margin:auto;
    background:rgba(255,255,255,.96);
    backdrop-filter:blur(10px);
    border:1px solid rgba(219,227,240,.85);
    border-radius:28px;
    box-shadow:var(--shadow);
    padding:28px;
}

/* ===== TITLE ===== */
h2{
    margin:0 0 18px;
    font-size:28px;
    letter-spacing:-.03em;
    line-height:1.1;
}

/* ===== FORM ===== */
.form-group{
    margin-bottom:16px;
    display:flex;
    flex-direction:column;
}

.form-group label{
    font-size:13px;
    font-weight:700;
    margin-bottom:7px;
    color:#334155;
}

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

.form-group textarea{
    resize:vertical;
    min-height:120px;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus{
    border-color:var(--primary);
    box-shadow:0 0 0 4px rgba(37,99,235,.12);
}

.form-group input:hover,
.form-group select:hover,
.form-group textarea:hover{
    border-color:#b9c7db;
}

/* ===== GRID ===== */
.grid{
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:16px;
}

/* ===== BUTTON ===== */
.btn{
    background:linear-gradient(135deg,var(--primary-dark),var(--primary));
    color:#fff;
    border:none;
    padding:13px 18px;
    border-radius:14px;
    font-weight:800;
    cursor:pointer;
    margin-top:10px;
    transition:.2s ease;
    box-shadow:0 10px 22px rgba(37,99,235,.20);
}

.btn:hover{
    transform:translateY(-1px);
    box-shadow:0 14px 26px rgba(37,99,235,.26);
}

/* ===== MESSAGE ===== */
.msg{
    background:#dcfce7;
    color:#166534;
    padding:12px 14px;
    border-radius:12px;
    margin-bottom:16px;
    font-weight:700;
    border:1px solid #bbf7d0;
}

/* ===== SECTION HEADINGS ===== */
h3{
    margin:22px 0 12px;
    font-size:18px;
    letter-spacing:-.02em;
    color:#0f172a;
    padding-bottom:8px;
    border-bottom:1px solid var(--border);
}

/* ===== SELECT2 ===== */
.select2-container--default .select2-selection--single{
    height:48px;
    border-radius:14px;
    border:1px solid var(--border)!important;
    padding:8px 12px;
    display:flex;
    align-items:center;
    background:#fff;
}

.select2-selection__rendered{
    display:flex!important;
    align-items:center;
    gap:10px;
    font-size:14px;
    color:var(--text);
}

.select2-container--default .select2-selection--single:hover{
    border-color:#b9c7db!important;
}

.select2-container--default .select2-selection--single:focus{
    border-color:var(--primary);
    box-shadow:0 0 0 4px rgba(37,99,235,.12);
}

.select2-dropdown{
    border-radius:14px;
    border:1px solid var(--border);
    background:#fff;
    box-shadow:0 18px 40px rgba(15,23,42,.12);
}

.select2-results__option{
    padding:10px;
    display:flex;
    align-items:center;
    gap:10px;
}

.select2-results__option--highlighted{
    background:var(--primary)!important;
    color:#fff!important;
}

.fi{
    width:20px;
    height:14px;
}

/* ===== TABLE WRAP ===== */
.table-wrap{
    width:100%;
    max-width:100%;
    overflow-x:auto;
    overflow-y:hidden;
    -webkit-overflow-scrolling:touch;
    border-radius:18px;
    margin-top:18px;
    border:1px solid var(--border);
    background:#fff;
    padding-bottom:8px;
    box-sizing:border-box;
}

/* scrollbar */
.table-wrap::-webkit-scrollbar{
    height:10px;
}
.table-wrap::-webkit-scrollbar-track{
    background:#e2e8f0;
    border-radius:20px;
}
.table-wrap::-webkit-scrollbar-thumb{
    background:#94a3b8;
    border-radius:20px;
}
.table-wrap::-webkit-scrollbar-thumb:hover{
    background:#64748b;
}

/* ===== TABLE ===== */
.table{
    width:max-content;
    min-width:100%;
    border-collapse:separate;
    border-spacing:0 10px;
    padding:0 10px 10px;
    table-layout:auto;
}

/* HEADER */
.table thead th{
    background:#334155;
    color:#fff;
    padding:14px 12px;
    font-size:13px;
    text-align:left;
    white-space:nowrap;
    line-height:1.25;
    min-width:140px;
    position:sticky;
    top:0;
    z-index:2;
}

/* DATA CELLS */
.table td{
    background:var(--soft);
    padding:14px 12px;
    font-size:14px;
    border-top:1px solid var(--border);
    border-bottom:1px solid var(--border);
    white-space:nowrap;
    min-width:140px;
    vertical-align:top;
}

/* smaller columns */
.table th:first-child,
.table td:first-child{
    min-width:70px;
}

.table th:last-child,
.table td:last-child{
    min-width:110px;
}

/* comments can be wider */
.table th:nth-last-child(3),
.table td:nth-last-child(3){
    min-width:220px;
    white-space:normal;
}

/* rounded corners */
.table thead th:first-child{
    border-radius:12px 0 0 12px;
}
.table thead th:last-child{
    border-radius:0 12px 12px 0;
}
.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;
}

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

/* INLINE EDIT */
.editable{
    cursor:pointer;
    transition:.2s ease;
    border-radius:8px;
}

.editable:hover{
    background:#eaf3ff;
}

.editable:focus{
    outline:2px solid rgba(37,99,235,.35);
    background:#e0f2fe;
}

.saved{
    background:#dcfce7 !important;
}

.error{
    background:#fee2e2 !important;
}

/* ACTION BUTTONS */
.action-buttons{
    display:flex;
    gap:8px;
    flex-wrap:nowrap;
}

/* ===== RESPONSIVE ===== */
@media(max-width:992px){
    .main-content{
        margin-left:0;
    }

    body{
        padding:70px 12px 14px;
    }

    .container{
        padding:18px;
        border-radius:22px;
        overflow:hidden;
    }

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


.btn-small{
    background:#e2e8f0;
    padding:8px 10px;
    border-radius:10px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border:none;
    cursor:pointer;
    color:#111827;
    transition:.2s ease;
}

.btn-small:hover{
    background:#cbd5e1;
    transform:translateY(-1px);
}

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

.pagination a{
    padding:9px 13px;
    border-radius:10px;
    border:1px solid var(--border);
    background:#fff;
    text-decoration:none;
    font-size:13px;
    font-weight:600;
}

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

/* ===== RESPONSIVE ===== */
@media(max-width:992px){
    .main-content{
        margin-left:0;
    }

    body{
        padding:70px 12px 14px;
        overflow-x:hidden;
    }

    .container{
        padding:18px;
        border-radius:22px;
    }

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

@media(max-width:768px){
    .table-wrap{
        overflow-x:auto;
        border-radius:14px;
    }

    .table{
        width:max-content;
        min-width:1800px;
    }

    .table thead{
        display:table-header-group;
    }

    .table tbody tr{
        display:table-row;
        background:transparent;
        margin:0;
        padding:0;
        border:none;
        box-shadow:none;
    }

    .table tbody td{
        display:table-cell;
        padding:14px 12px;
        border-top:1px solid var(--border);
        border-bottom:1px solid var(--border);
        font-size:13px;
    }

    .table tbody td::before{
        content:none;
    }

    .action-buttons{
        justify-content:flex-start;
    }
}
</style>
</head>
<body>

<?php if (file_exists('rasidebar.php')) include 'rasidebar.php'; ?>
<?php if (file_exists('../header.php')) include '../header.php'; ?>

<div class="main-content">
    <div class="container">
        <h2>Sample Product</h2>

        <?php if ($msg): ?>
            <div class="msg"><?php echo htmlspecialchars($msg, ENT_QUOTES); ?></div>
        <?php endif; ?>

      <form method="POST" enctype="multipart/form-data" style="width:100%; max-width:100%; overflow:hidden;">

    <div class="grid" style="width:100%; max-width:100%;">

        <div class="form-group">
            <label>Product Name *</label>
            <input type="text" name="product_name" value="<?=e($data['product_name'])?>" required>
        </div>

        <div class="form-group">
            <label>Brand Name</label>
            <input type="text" name="brand_name" value="<?=e($data['brand_name'])?>">
        </div>

        <div class="form-group">
            <label>Packing</label>
            <input type="text" name="packing" value="<?=e($data['packing'])?>">
        </div>

        <div class="form-group">
            <label>Batch No</label>
            <input type="text" name="batch_no" value="<?=e($data['batch_no'])?>">
        </div>

        <div class="form-group">
            <label>Manufacturing Date</label>
            <input type="date" name="manufacturing_date" value="<?=e($data['manufacturing_date'])?>">
        </div>

        <div class="form-group">
            <label>Expiry Date</label>
            <input type="date" name="expiry_date" value="<?=e($data['expiry_date'])?>">
        </div>

        <div class="form-group">
            <label>Manufactured By</label>
            <input type="text" name="manufactured_by" value="<?=e($data['manufactured_by'])?>">
        </div>

        <div class="form-group">
            <label>Received On</label>
            <input type="date" name="received_on" value="<?=e($data['received_on'])?>">
        </div>

        <div class="form-group">
            <label>Received By</label>
            <input type="text" name="received_by" value="<?=e($data['received_by'])?>">
        </div>

        <div class="form-group">
            <label>Received Qty</label>
            <input type="number" name="received_qty" value="<?=e($data['received_qty'])?>">
        </div>

        <div class="form-group">
            <label>Sent On</label>
            <input type="date" name="sent_on" value="<?=e($data['sent_on'])?>">
        </div>

        <div class="form-group">
            <label>Sent By</label>
            <input type="text" name="sent_by" value="<?=e($data['sent_by'])?>">
        </div>

        <div class="form-group">
            <label>Sent To</label>
            <input type="text" name="sent_to" value="<?=e($data['sent_to'])?>">
        </div>

        <div class="form-group">
            <label>Sent Qty</label>
            <input type="number" name="sent_qty" value="<?=e($data['sent_qty'])?>">
        </div>

        <div class="form-group">
            <label>Remaining Qty</label>
            <input type="number" name="remaining_qty" value="<?=e($data['remaining_qty'])?>">
        </div>

        <div class="form-group">
            <label>Tracking Number</label>
            <input type="text" name="tracking_number" value="<?=e($data['tracking_number'])?>">
        </div>

    </div>

    <div class="form-group" style="width:100%;">
        <label>Comments</label>
        <textarea 
            name="comments" 
            rows="4"
            style="width:100%; max-width:100%; padding:13px 14px; border:1px solid var(--border); border-radius:14px; resize:vertical;"
        ><?=e($data['comments'])?></textarea>
    </div>

    <div class="form-group" style="width:100%;">
        <label>Upload Documents</label>
        <input type="file" name="document" style="width:100%; max-width:100%;">
    </div>

    <button type="submit" name="submit" class="btn">Save Product</button>

</form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
function getFlagCode(name) {
    const map = {
        "India": "in",
        "Afghanistan": "af",
        "Australia": "au",
        "Bangladesh": "bd",
        "France": "fr",
        "Germany": "de",
        "Canada": "ca",
        "United States": "us",
        "United Kingdom": "gb",
        "UAE": "ae",
        "Russia": "ru"
    };

    return map[(name || "").trim()] || "";
}
function formatCountry(option) {
    if (!option.id) return option.text;

    const flag = getFlagCode(option.text);
    if (!flag) return option.text;

    return $(
        '<span style="display:flex;align-items:center;gap:10px;">' +
        '<span class="fi fi-' + flag + '"></span>' +
        '<span>' + option.text + '</span>' +
        '</span>'
    );
}

$('#country').select2({
    templateResult: formatCountry,
    templateSelection: formatCountry,
    placeholder: "Select Country",
    width: '100%',
    dropdownPosition: 'below'
});

/* 🔥 ADD SEARCH PLACEHOLDER */
$(document).on('select2:open', function () {
    document.querySelector('.select2-search__field').placeholder = 'Search country...';
});
function toggleGstTax(countryName) {
    let isIndia = (countryName || '').toLowerCase() === 'india';

    if (isIndia) {
        $('#gstBox').show();
        $('#taxBox').hide();
        $('#taxInput').val('');
    } else {
        $('#gstBox').hide();
        $('#taxBox').show();
        $('#gstSelect').val('');
    }
}

$('#country').on('change', function () {
    toggleGstTax($(this).val());
});

/* page load */
toggleGstTax($('#country').val());
</script>

</body>
</html>