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

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

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

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

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

$errors = [];
$success = null;

$form = [
    'product_name'    => '',
    'generic_name'    => '',
    'brand_name'      => '',
    'standards'       => '',
    'strength'        => '',
    'volume'          => '',
    'dosage_form'     => '',
    'shelf_life'      => '',
    'indication'      => '',
    'packing'         => '',
    'manufactured_by' => '',
    'marketed_by'     => '',
    'distributed_by'   => '',
    'country_id'      => '',
    'dossier_type'    => '',
];

$edit_id = (int)($_GET['id'] ?? $_POST['product_id'] ?? 0);
$is_edit = $edit_id > 0;

/* Load existing product for edit */
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()) {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $form['product_name']    = $row['product_name'] ?? '';
                $form['generic_name']    = $row['generic_name'] ?? '';
                $form['brand_name']      = $row['brand_name'] ?? '';
                $form['standards']       = $row['standards'] ?? '';
                $form['strength']        = $row['strength'] ?? '';
                $form['volume']          = $row['volume'] ?? '';
                $form['dosage_form']     = $row['dosage_form'] ?? '';
                $form['shelf_life']      = $row['shelf_life'] ?? '';
                $form['indication']      = $row['indication'] ?? '';
                $form['packing']         = $row['primary_packing'] ?? '';
                $form['manufactured_by'] = $row['manufactured_by'] ?? '';
                $form['marketed_by']     = $row['marketed_by'] ?? '';
                $form['distributed_by']  = $row['distributed_by'] ?? '';
                $form['country_id']      = $row['country_id'] ?? '';
                $form['dossier_type']    = $row['dossier_type'] ?? '';
            }
        } 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 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_product'])) {

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

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

// All fields required validation
foreach ($form as $key => $value) {

    if ($key === 'shelf_life') continue; // skip

    if ($value === '') {
        $fieldName = ucwords(str_replace('_', ' ', $key));
        $errors[$key] = "$fieldName is required.";
    }
}

    $country_id = (int)$form['country_id'];

    if (empty($errors)) {
        if ($is_edit && $edit_id > 0) {
           $variation_json = json_encode([
    'product_name'           => $form['product_name'],
    'generic_name'           => $form['generic_name'],
    'brand_name'             => $form['brand_name'],
    'standards'              => $form['standards'],
    'strength'               => $form['strength'],
    'volume'                 => $form['volume'],
    'dosage_form'            => $form['dosage_form'],
    'shelf_life'             => $form['shelf_life'],
    'indication'             => $form['indication'],
    'packing'                => $form['packing'],
    'manufactured_by'        => $form['manufactured_by'],
    'marketed_by'            => $form['marketed_by'],
    'distributed_by'         => $form['distributed_by'],
    'country_id'             => $country_id,
    'dossier_type'           => $form['dossier_type'],
    'variation_type'         => 'Product Update',
    'variation_description'  => 'Product edited and sent for approval',
    'submission_date'        => date('Y-m-d')
]);

$sql = "INSERT INTO admin_product_approval (
    product_id,
    product_name,
    variation,
    type,
    status,
    created_at
) VALUES (
    ?,
    ?,
    ?,
    'variation',
    'pending',
    NOW()
)";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    $errors[] = 'Prepare failed: ' . $conn->error;
} else {

    $stmt->bind_param(
        "iss",
        $edit_id,
        $form['product_name'],
        $variation_json
    );

    if ($stmt->execute()) {
        header("Location: product_request.php?variation=1");
        exit;
    } else {
        $errors[] = 'Execute failed: ' . $stmt->error;
    }

    $stmt->close();
}
        } else {

    $variation_json = json_encode([
        'product_name'     => $form['product_name'],
        'generic_name'     => $form['generic_name'],
        'brand_name'       => $form['brand_name'],
        'standards'        => $form['standards'],
        'strength'         => $form['strength'],
        'volume'           => $form['volume'],
        'dosage_form'      => $form['dosage_form'],
        'shelf_life'       => $form['shelf_life'],
        'indication'       => $form['indication'],
        'packing'          => $form['packing'],
        'manufactured_by'  => $form['manufactured_by'],
        'marketed_by'      => $form['marketed_by'],
        'distributed_by'   => $form['distributed_by'],
        'country_id'       => $country_id,
        'dossier_type'     => $form['dossier_type']
    ]);

    $sql = "INSERT INTO admin_product_approval (
        product_id,
        product_name,
        variation,
        type,
        status,
        created_at
    ) VALUES (
        0,
        ?,
        ?,
        'add',
        'pending',
        NOW()
    )";

    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        $errors[] = 'Prepare failed: ' . $conn->error;
    } else {

        $stmt->bind_param(
            "ss",
            $form['product_name'],
            $variation_json
        );

        if ($stmt->execute()) {
            header("Location: product_request.php?added=1");
            exit;
        } else {
            $errors[] = 'Execute failed: ' . $stmt->error;
        }

        $stmt->close();
    }
}
    }
}

/* Countries */
$countries = [];
$res = $conn->query("SELECT id, country_name FROM countries ORDER BY country_name");
if ($res) {
    while ($r = $res->fetch_assoc()) $countries[] = $r;
}
?>
<!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'; ?> Product</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{
    --bg:#eef2f7;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#64748b;
    --primary:#1e3a8a;
    --primary-dark:#0f172a;
    --border:#e2e8f0;
    --success-bg:#dcfce7;
    --success-text:#166534;
    --danger-bg:#fee2e2;
    --danger-text:#991b1b;
}

*{
    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(30,58,138,.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;
}

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

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

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

/* SECTION */
.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(30,58,138,.12);
}

/* FORM */
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;
    box-shadow:0 0 0 4px rgba(30,58,138,.08);
}

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

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

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

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

.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(30,58,138,.18);
    transition:.18s ease;
    text-decoration:none;
    min-width:150px;
}

.btn:hover{
    transform:translateY(-1px);
    background:var(--primary);
}

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

/* ALERTS */
.error{
    background:var(--danger-bg);
    color:var(--danger-text);
    padding:14px 16px;
    border-radius:14px;
    margin-bottom:16px;
    font-weight:600;
}

.success{
    background:var(--success-bg);
    color:var(--success-text);
    padding:14px 16px;
    border-radius:14px;
    margin-bottom:16px;
    font-weight:600;
}

/* SMALL TEXT */
.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 DROPDOWN */
.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;
}

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

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

    .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%;
    }
}

</style>
</head>
<body>
<?php include 'adminsidebar.php'; ?>
<?php if (file_exists('../header.php')) include '../header.php'; ?>

<div class="container">
  <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" 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; ?>

      <div class="section">
        <h3>Product Information</h3>

        <label>Product Name *</label>
        <input name="product_name" value="<?php echo e($form['product_name']); ?>" 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']); ?>">
          </div>
          <div>
            <label>Brand Name</label>
            <input name="brand_name" value="<?php echo e($form['brand_name']); ?>">
          </div>
        </div>

        <div class="grid">
          <div>
            <label>Standard</label>
            <input name="standards" value="<?php echo e($form['standards']); ?>">
          </div>
          <div>
            <label>Strength</label>
            <input name="strength" value="<?php echo e($form['strength']); ?>">
          </div>
        </div>

        <div class="grid">
          <div>
            <label>Volume</label>
            <input name="volume" value="<?php echo e($form['volume']); ?>">
          </div>
          <div>
            <label>Dosage Form</label>
            <input name="dosage_form" value="<?php echo e($form['dosage_form']); ?>">
          </div>
        </div>

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

      <div class="section">
        <h3>Packing & Manufacturer</h3>

        <label>Packing</label>
        <input name="packing" value="<?php echo e($form['packing']); ?>">

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

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

      <div class="section">
        <h3>Country & Dossier</h3>

        <div class="grid">
          <div>
            <label>Country *</label>
            <input type="hidden" name="country_id" id="countryInput" value="<?php echo e($form['country_id']); ?>">

            <div class="country-wrapper">
              <button type="button" class="input country-display <?php echo ($form['country_id']==='' && !empty($errors)) ? 'error-border' : ''; ?>" id="countryDisplay">
                <span id="countryDisplayText">
                  <?php
                  $selectedCountry = 'Select country';
                  foreach ($countries as $c) {
                      if ((string)$c['id'] === (string)$form['country_id']) {
                          $selectedCountry = $c['country_name'];
                          break;
                      }
                  }
                  echo e($selectedCountry);
                  ?>
                </span>
                <i class="fa fa-angle-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>
            <label>Type of dossier *</label>
            <select name="dossier_type" class="<?php echo ($form['dossier_type']==='' && !empty($errors)) ? 'error-border' : ''; ?>">
              <option value="">Select Type</option>
              <option value="new" <?php echo ($form['dossier_type']==='new') ? 'selected' : ''; ?>>New</option>
              <option value="renewal" <?php echo ($form['dossier_type']==='renewal') ? 'selected' : ''; ?>>Renewal</option>
            </select>
            <?php echo showError($errors, 'dossier_type'); ?>
          </div>
        </div>
      </div>

      <div class="section">
        <div class="actions">
          <button class="btn" type="submit" name="add_product"><?php echo $is_edit ? 'Save Changes' : 'Save Product'; ?></button>
          <a class="btn-secondary" href="products.php" style="display:inline-block;padding:10px 14px;text-decoration:none;color:#000">Back to list</a>
        </div>
      </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");

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

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

document.querySelectorAll(".country-item").forEach(item => {
  item.onclick = () => {
    input.value = item.dataset.id;
    displayText.innerHTML = `<img class="country-flag" src="${item.querySelector("img").src}"> ${item.dataset.name}`;
    dropdown.style.display = "none";
  };
});

document.addEventListener("click", function(e){
    if (!document.querySelector(".country-wrapper").contains(e.target)) {
        dropdown.style.display = "none";
    }
});
</script>
</body>
</html>