<?php
require_once("../php/db_connect.php");

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$shop_id = $_SESSION["user_id"] ?? 0;

if ($shop_id == 0) {
    echo "<script>window.location='login.php';</script>";
    exit;
}

/* =========================
   LOAD SERVICE TYPES
========================= */
$stmt_types = $conn->prepare("
    SELECT id, type_name
    FROM service_type_options
    WHERE status = 'active' AND owner_shop_id = ?
    ORDER BY type_name ASC
");

$stmt_types->bind_param("i", $shop_id);
$stmt_types->execute();
$service_types = $stmt_types->get_result();

/* =========================
   LOAD SUB TYPES
========================= */
$subtype_map = [];

$stmt_subtypes = $conn->prepare("
    SELECT service_type_id, subtype_name
    FROM service_subtype_options
    WHERE status = 'active' AND owner_shop_id = ?
    ORDER BY subtype_name ASC
");

$stmt_subtypes->bind_param("i", $shop_id);
$stmt_subtypes->execute();
$subtypes_result = $stmt_subtypes->get_result();

while ($row = $subtypes_result->fetch_assoc()) {
    $type_id = (int)$row["service_type_id"];
    $subtype_name = trim($row["subtype_name"]);

    if (!isset($subtype_map[$type_id])) {
        $subtype_map[$type_id] = [];
    }

    $subtype_map[$type_id][] = $subtype_name;
}

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

    $service_name = trim($_POST["service_name"] ?? "");
    $description = trim($_POST["description"] ?? "");
    $service_type = trim($_POST["service_type"] ?? "");
    $min_order_quantity = !empty($_POST["min_order_quantity"]) ? (int)$_POST["min_order_quantity"] : 1;
    $estimated_days = !empty($_POST["estimated_days"]) ? (int)$_POST["estimated_days"] : 1;
    $is_featured = isset($_POST["is_featured"]) ? 1 : 0;
    $status = trim($_POST["status"] ?? "active");

    $sizes = $_POST["sizes"] ?? [];
    $variant_prices = $_POST["variant_prices"] ?? [];

    if ($service_type === "" || $service_name === "") {
        echo "<script>alert('Please select service type and sub type.'); window.history.back();</script>";
        exit;
    }

    /* =========================
       VALIDATE VARIANTS
    ========================= */
    $valid_variants = [];

    foreach ($sizes as $index => $size) {
        $size = trim($size);
        $price = isset($variant_prices[$index]) ? (float)$variant_prices[$index] : 0;

        if ($size !== "" && $price > 0) {
            $valid_variants[] = [
                "size" => $size,
                "price" => $price
            ];
        }
    }

    if (empty($valid_variants)) {
        echo "<script>alert('Please add at least one size/option with price.'); window.history.back();</script>";
        exit;
    }

    /*
      Compatibility only:
      Your current services table still has size and price columns.
      The real sizes and prices will be saved in service_variants.
    */
    $base_size = "";
    $base_price = min(array_column($valid_variants, "price"));

    /* =========================
       IMAGE UPLOAD
    ========================= */
    $service_image = "";

    if (!empty($_FILES["service_image"]["name"])) {

        $upload_dir = "../uploads/services/";

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $file_name = $_FILES["service_image"]["name"];
        $file_tmp = $_FILES["service_image"]["tmp_name"];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        $allowed_types = ["jpg", "jpeg", "png", "webp"];

        if (!in_array($file_ext, $allowed_types)) {
            echo "<script>alert('Invalid image format. Please upload JPG, JPEG, PNG, or WEBP only.'); window.history.back();</script>";
            exit;
        }

        $service_image = "service_" . $shop_id . "_" . time() . "." . $file_ext;
        $target = $upload_dir . $service_image;

        if (!move_uploaded_file($file_tmp, $target)) {
            echo "<script>alert('Image upload failed.'); window.history.back();</script>";
            exit;
        }
    }

    /* =========================
       INSERT MAIN SERVICE
    ========================= */
    $stmt = $conn->prepare("
        INSERT INTO services
        (
            owner_shop_id,
            service_name,
            size,
            description,
            price,
            service_type,
            service_image,
            min_order_quantity,
            estimated_days,
            is_featured,
            status
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param(
        "isssdssiiis",
        $shop_id,
        $service_name,
        $base_size,
        $description,
        $base_price,
        $service_type,
        $service_image,
        $min_order_quantity,
        $estimated_days,
        $is_featured,
        $status
    );

    if ($stmt->execute()) {

        $service_id = $stmt->insert_id;

        /* =========================
           INSERT SIZES / OPTIONS
        ========================= */
        foreach ($valid_variants as $variant) {

            $variant_size = $variant["size"];
            $variant_price = $variant["price"];

            $stmt_variant = $conn->prepare("
                INSERT INTO service_variants
                (service_id, size, price, is_available)
                VALUES (?, ?, ?, 1)
            ");

            if (!$stmt_variant) {
                die("Variant prepare failed: " . $conn->error);
            }

            $stmt_variant->bind_param(
                "isd",
                $service_id,
                $variant_size,
                $variant_price
            );

            $stmt_variant->execute();
        }

        echo "<script>window.location='admin.php?page=services&message=added';</script>";
        exit;

    } else {
        die("Insert failed: " . $stmt->error);
    }
}
?>

<div class="add-service-page">
    <div class="add-service-card">

        <div class="add-service-header">
            <div>
                <h1>Add Service</h1>
                <p>Create a new service for your shop.</p>
            </div>

            <a href="admin.php?page=services" class="close-link">×</a>
        </div>

        <form method="POST" enctype="multipart/form-data" class="add-service-form">

            <div class="form-group">
                <label>Service Type <span>*</span></label>

                <select name="service_type" id="service_type" required>
                    <option value="">Select Service Type</option>

                    <?php while ($type = $service_types->fetch_assoc()): ?>
                        <option
                            value="<?php echo htmlspecialchars($type['type_name']); ?>"
                            data-type-id="<?php echo (int)$type['id']; ?>">
                            <?php echo htmlspecialchars($type['type_name']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Sub Type <span>*</span></label>

                <select name="service_name" id="service_name" required>
                    <option value="">Select Sub Type</option>
                </select>
            </div>

            <div class="form-group" id="variant-group" style="display:none;">
                <label id="variant-label">Sizes / Options and Prices <span>*</span></label>

                <div class="variant-note">
                    Add all available sizes/options here. Example: S - ₱260, M - ₱260, 3XL - ₱330.
                </div>

                <div id="variant-options"></div>

                <button type="button" class="add-size-btn" id="addVariant">
                    + Add Size / Option
                </button>
            </div>

            <div class="form-group">
                <label>Description</label>
                <textarea name="description" rows="4" placeholder="Write a short description of the service..."></textarea>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label>Minimum Quantity</label>
                    <input type="number" name="min_order_quantity" min="1" value="1">
                </div>

                <div class="form-group">
                    <label>Estimated Days</label>
                    <input type="number" name="estimated_days" min="1" value="1">
                </div>

                <div class="form-group">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" selected>Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label>Service Image</label>
                <input type="file" name="service_image" accept="image/*">
            </div>

            <div class="form-check">
                <label>
                    <input type="checkbox" name="is_featured" value="1">
                    Featured Service
                </label>
            </div>

            <div class="form-actions">
                <button type="submit" class="save-btn">Save Service</button>
                <a href="admin.php?page=services" class="cancel-btn">Cancel</a>
            </div>

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

<style>
.add-service-page {
    padding: 25px;
}

.add-service-card {
    background: #fff;
    padding: 25px;
    border-radius: 14px;
    max-width: 1050px;
    box-shadow: 0 4px 18px rgba(0,0,0,0.08);
}

.add-service-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 22px;
}

.add-service-header h1 {
    font-size: 26px;
    margin: 0 0 5px;
    color: #111827;
}

.add-service-header p {
    color: #6b7280;
    margin: 0;
}

.close-link {
    text-decoration: none;
    font-size: 28px;
    color: #6b7280;
    line-height: 1;
}

.close-link:hover {
    color: #111827;
}

.add-service-form .form-group {
    margin-bottom: 18px;
}

.add-service-form label {
    display: block;
    font-weight: 600;
    margin-bottom: 7px;
    color: #111827;
}

.add-service-form label span {
    color: #dc3545;
}

.add-service-form input,
.add-service-form select,
.add-service-form textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 7px;
    outline: none;
    font-size: 14px;
}

.add-service-form input:focus,
.add-service-form select:focus,
.add-service-form textarea:focus {
    border-color: #16a7e3;
    box-shadow: 0 0 0 3px rgba(22,167,227,0.12);
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
}

.variant-note {
    font-size: 13px;
    color: #6b7280;
    margin-bottom: 10px;
}

.variant-row {
    display: grid;
    grid-template-columns: 1fr 1fr auto;
    gap: 10px;
    margin-bottom: 10px;
    align-items: center;
}

.variant-row input {
    width: 100%;
}

.remove-size-btn {
    background: #dc3545;
    color: #fff;
    border: none;
    padding: 10px 14px;
    border-radius: 7px;
    cursor: pointer;
}

.remove-size-btn:hover {
    background: #bb2d3b;
}

.add-size-btn {
    margin-top: 8px;
    background: #e9f7fd;
    color: #087ea4;
    border: 1px solid #b8e7f8;
    padding: 9px 14px;
    border-radius: 7px;
    cursor: pointer;
    font-weight: 600;
}

.add-size-btn:hover {
    background: #d6f1fb;
}

.form-check {
    margin: 15px 0;
}

.form-check input {
    width: auto;
    margin-right: 8px;
}

.form-actions {
    margin-top: 22px;
    display: flex;
    gap: 10px;
}

.save-btn {
    background: #26354d;
    color: white;
    border: none;
    padding: 10px 18px;
    border-radius: 7px;
    cursor: pointer;
    font-weight: 600;
}

.save-btn:hover {
    background: #1d293d;
}

.cancel-btn {
    background: #eeeeee;
    color: #222;
    text-decoration: none;
    padding: 10px 18px;
    border-radius: 7px;
    font-weight: 600;
}

.cancel-btn:hover {
    background: #e0e0e0;
}

@media (max-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr;
    }

    .variant-row {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function () {

    const serviceTypeSelect = document.getElementById("service_type");
    const serviceNameSelect = document.getElementById("service_name");

    const variantGroup = document.getElementById("variant-group");
    const variantLabel = document.getElementById("variant-label");
    const variantOptions = document.getElementById("variant-options");
    const addVariantBtn = document.getElementById("addVariant");

    const subtypeMap = <?php echo json_encode($subtype_map); ?>;

    const sizeConfig = {
        jersey: {
            label: "Sizes and Prices",
            options: ["S", "M", "L", "XL", "2XL", "3XL"]
        },
        mug: {
            label: "Mug Sizes and Prices",
            options: ["11 oz", "12 oz", "15 oz", "20 oz travel mug"]
        },
        tarpaulin: {
            label: "Tarpaulin Sizes and Prices",
            options: [
                "2x3 ft",
                "3x4 ft",
                "3x6 ft",
                "4x6 ft",
                "4x8 ft",
                "5x7 ft",
                "6x8 ft",
                "6x10 ft",
                "8x10 ft"
            ]
        }
    };

    function normalizeText(text) {
        return (text || "").trim().toLowerCase();
    }

    function createVariantRow(size = "", readonly = false) {
        const row = document.createElement("div");
        row.className = "variant-row";

        row.innerHTML = `
            <input
                type="text"
                name="sizes[]"
                value="${size}"
                placeholder="Size / Option e.g. S, M, 3XL, Standard"
                ${readonly ? "readonly" : ""}
                required
            >

            <input
                type="number"
                name="variant_prices[]"
                step="0.01"
                min="0.01"
                placeholder="Price"
                required
            >

            <button type="button" class="remove-size-btn">×</button>
        `;

        return row;
    }

    function renderVariants(selectedType) {
        variantOptions.innerHTML = "";

        if (!selectedType) {
            variantGroup.style.display = "none";
            return;
        }

        if (sizeConfig[selectedType]) {
            variantLabel.innerHTML = sizeConfig[selectedType].label + ' <span>*</span>';

            sizeConfig[selectedType].options.forEach(function (size) {
                variantOptions.appendChild(createVariantRow(size, true));
            });
        } else {
            variantLabel.innerHTML = 'Option and Price <span>*</span>';
            variantOptions.appendChild(createVariantRow("Standard", false));
        }

        variantGroup.style.display = "block";
    }

    function populateSubtypes() {
        const selectedOption = serviceTypeSelect.options[serviceTypeSelect.selectedIndex];
        const typeId = selectedOption ? selectedOption.getAttribute("data-type-id") : null;

        serviceNameSelect.innerHTML = '<option value="">Select Sub Type</option>';

        if (!typeId || !subtypeMap[typeId]) {
            return;
        }

        subtypeMap[typeId].forEach(function (name) {
            const option = document.createElement("option");
            option.value = name;
            option.textContent = name;
            serviceNameSelect.appendChild(option);
        });
    }

    serviceTypeSelect.addEventListener("change", function () {
        const selectedType = normalizeText(serviceTypeSelect.value);

        populateSubtypes();
        renderVariants(selectedType);
    });

    addVariantBtn.addEventListener("click", function () {
        variantOptions.appendChild(createVariantRow("", false));
    });

    document.addEventListener("click", function (e) {
        if (e.target.classList.contains("remove-size-btn")) {
            const rows = variantOptions.querySelectorAll(".variant-row");

            if (rows.length > 1) {
                e.target.closest(".variant-row").remove();
            } else {
                alert("At least one size or option is required.");
            }
        }
    });

});
</script>