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

$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;
}

/* ================= DEFAULT VALUES ================= */
$data = [
'product_name'=>'',
'generic_name'=>'',
'brand_name'=>'',
'country'=>'',
'packet_qty'=>'',
'units_packet'=>'',
'price_packet'=>'',
'gst_percent'=>'',
'tax_percent'=>'',
'document'=>''
];

/* ================= 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']);
    $generic_name = trim($_POST['generic_name']);
    $brand_name   = trim($_POST['brand_name']);
    $country      = trim($_POST['country']);
    $packet_qty   = (int)$_POST['packet_qty'];
    $units_packet = (int)$_POST['units_packet'];
    $price_packet = (float)$_POST['price_packet'];

    $gst = ($country === 'India') ? (float)$_POST['gst_percent'] : 0;
    $tax = ($country !== 'India') ? (float)$_POST['tax_percent'] : 0;

    /* 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){
        /* UPDATE */
        $stmt = $conn->prepare("UPDATE sample_products SET
        product_name=?, generic_name=?, brand_name=?, country=?,
        packet_qty=?, units_packet=?, price_packet=?, gst_percent=?, tax_percent=?, document=?
        WHERE id=?");

        $stmt->bind_param("ssssiidddsi",
            $product_name,
            $generic_name,
            $brand_name,
            $country,
            $packet_qty,
            $units_packet,
            $price_packet,
            $gst,
            $tax,
            $file_name,
            $id
        );

    } else {
        /* INSERT */
        $stmt = $conn->prepare("INSERT INTO sample_products
        (product_name,generic_name,brand_name,country,packet_qty,units_packet,price_packet,gst_percent,tax_percent,document)
        VALUES (?,?,?,?,?,?,?,?,?,?)");

        $stmt->bind_param("ssssiiddds",
            $product_name,
            $generic_name,
            $brand_name,
            $country,
            $packet_qty,
            $units_packet,
            $price_packet,
            $gst,
            $tax,
            $file_name
        );
    }

    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>
body {
    font-family: Arial, sans-serif;
    background: #f4f6f9;
    margin: 0;
}

.main-content {
    margin-left: 220px;
    padding: 20px;
}

.container {
    width: 70%;
    margin: auto;
    background: #fff;
    padding: 25px;
    border-radius: 10px;
    box-shadow: 0 0 15px rgba(0,0,0,0.1);
}

h2 {
    margin-bottom: 20px;
}

.msg {
    background: #d4edda;
    color: #155724;
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 5px;
}

.form-group {
    margin-bottom: 15px;
    display: flex;
    flex-direction: column;
}

.form-group label {
    font-weight: 600;
    margin-bottom: 5px;
}

.form-group input,
.form-group select {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 6px;
    width: 100%;
    box-sizing: border-box;
}

.grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
}

.btn {
    background: #1b80e4;
    color: #fff;
    border: none;
    padding: 12px;
    border-radius: 6px;
    cursor: pointer;
    width: 100%;
    margin-top: 10px;
}

.btn:hover {
    background: #181b1f;
}
/* SELECT2 FIXED UI */
.select2-container--default .select2-selection--single {
    height: 44px;
    border-radius: 8px;
    border: 1px solid #d1d5db;
    padding: 6px 10px;
    display: flex;
    align-items: center;
    transition: 0.2s;
}

.select2-container--default .select2-selection--single:hover {
    border-color: #0c0d0f;
}

.select2-container--default .select2-selection--single:focus {
    border-color: #2752be;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
}

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

/* DROPDOWN */
.select2-dropdown {
    border-radius: 10px;
    border: 1px solid #e5e7eb;
    box-shadow: 0 10px 25px rgba(0,0,0,0.08);
}
/* FORCE DROPDOWN BELOW */
.select2-container--open .select2-dropdown {
    top: 100% !important;
    bottom: auto !important;
}

/* FIX POSITION */
.select2-container--open {
    z-index: 9999;
}

/* OPTIONAL: ADD SPACE BELOW INPUT */
.select2-container {
    margin-bottom: 5px;
}
/* SEARCH BOX */
.select2-search__field {
    border-radius: 6px !important;
    padding: 8px !important;
}

/* OPTIONS */
.select2-results__option {
    padding: 10px 12px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
}

/* HOVER */
.select2-results__option--highlighted {
    background: #383c46 !important;
    color: #fff !important;
}

/* FLAG SIZE */
.fi {
    width: 20px;
    height: 14px;
    border-radius: 2px;
}

/* REMOVE DEFAULT ARROW STYLE */
.select2-selection__arrow {
    height: 100% !important;
    right: 10px !important;
}
</style>
</head>
<body>

<?php if (file_exists('adminsidebar.php')) include 'adminsidebar.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">

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

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

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

            <div class="grid">
                <div class="form-group">
                    <label>Country</label>
                    <select name="country" id="country" style="width:100%">

                    <option value="">Select Country</option>

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

                    <option value="<?=e($c['country_name'])?>"
                    <?=($data['country'] == $c['country_name'] ? 'selected' : '')?>>

                    <?=e($c['country_name'])?>

                    </option>

                    <?php endforeach; ?>

                    </select>
                </div>

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

            <div class="grid">
                <div class="form-group">
                    <label>Units per Packet</label>
                    <input type="number" name="units_packet" value="<?=e($data['units_packet'])?>">
                </div>

                <div class="form-group">
                    <label>Price per Packet</label>
                    <input type="number" name="price_packet" value="<?=e($data['price_packet'])?>">
                </div>
            </div>

            <!-- ✅ FIXED GST + TAX -->
            <div class="grid">

                <div class="form-group" id="gstBox">
                    <label>GST (%)</label>
                    <select name="gst_percent" id="gstSelect">
                        <option value="">Select GST</option>
                        <option value="0" <?=($data['gst_percent']==0?'selected':'')?> >0%</option>
                        <option value="5" <?=($data['gst_percent']==5?'selected':'')?> >5%</option>
                        <option value="12" <?=($data['gst_percent']==12?'selected':'')?> >12%</option>
                        <option value="18" <?=($data['gst_percent']==18?'selected':'')?> >18%</option>
                    </select>
                </div>

                <div class="form-group" id="taxBox">
                    <label>Tax (%)</label>
                    <input type="number" name="tax_percent" value="<?=e($data['tax_percent'])?>">
                </div>

            </div>

            <div class="form-group">
                <label>Upload Document</label>
                <input type="file" name="document">
            </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>