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

$product_id = (int)($_GET['product_id'] ?? $_POST['product_id'] ?? 0);

if ($product_id <= 0) {
    die("Invalid Product ID");
}

/* PRODUCT DETAILS */
$stmt = $conn->prepare("SELECT * FROM products WHERE id=?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$product = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$product) {
    die("Product not found");
}

/* NEXT VARIATION NUMBER */
$stmt = $conn->prepare("SELECT MAX(variation_no) as last_no FROM product_variations WHERE product_id=?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$last = $stmt->get_result()->fetch_assoc();
$stmt->close();

$variation_no = (int)($last['last_no'] ?? 0) + 1;

/* SAVE */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $variation_type = trim($_POST['variation_type']);
    $description    = trim($_POST['description']);
    $submission_date= $_POST['submission_date'] ?: null;
    $approval_date  = $_POST['approval_date'] ?: null;
    $comments       = trim($_POST['comments']);

    $document = '';

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

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

        $fileName = time() . "_" . basename($_FILES['document']['name']);
        $target = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES['document']['tmp_name'], $target)) {
            $document = "uploads/variations/" . $fileName;
        }
    }

    $stmt = $conn->prepare("
    INSERT INTO product_variations
    (product_id, variation_no, variation_type, variation_description, submission_date, approval_date, comments, document_file)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");

    $stmt->bind_param(
        "iissssss",
        $product_id,
        $variation_no,
        $variation_type,
        $description,
        $submission_date,
        $approval_date,
        $comments,
        $document
    );

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

   header("Location: add_product.php?id=".$product_id."&variation_added=1");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Add Variation</title>
    <style>
        body{font-family:Arial;background:#f4f6f9;padding:20px;}
        .card{max-width:900px;margin:auto;background:#fff;padding:25px;border-radius:12px;box-shadow:0 5px 20px rgba(0,0,0,.08);}
        h2{margin-bottom:20px;}
        .grid{display:grid;grid-template-columns:repeat(2,1fr);gap:15px;}
        input,select,textarea{
            width:100%;
            padding:12px;
            border:1px solid #ccc;
            border-radius:8px;
        }
        textarea{min-height:100px;}
        button{
            background:#374151;
            color:#fff;
            padding:12px 18px;
            border:none;
            border-radius:8px;
            cursor:pointer;
        }
        button:hover{background:#111827;}
    </style>
</head>
<body>

<div class="card">
    <h2>Add Variation - <?php echo e($product['product_name']); ?></h2>

    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">

        <div class="grid">
            <input type="text" value="Variation #<?php echo $variation_no; ?>" readonly>

            <select name="variation_type" required>
                <option value="">Select Variation Type</option>
                <option>Packing Change</option>
                <option>Brand Change</option>
                <option>Strength Change</option>
                <option>Volume Change</option>
                <option>Manufacturer Change</option>
                <option>Label Update</option>
                <option>Other</option>
            </select>

            <input type="date" name="submission_date">

            <input type="date" name="approval_date">

            <input type="file" name="document" accept=".pdf">
        </div>

        <br>

        <textarea name="description" placeholder="Description of Variation"></textarea>

        <br><br>

        <textarea name="comments" placeholder="Comments"></textarea>

        <br><br>

        <button type="submit">Save Variation</button>
        <a href="view_variations.php?product_id=<?php echo $product_id; ?>">View Variations</a>
    </form>
</div>

</body>
</html>