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

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

if (!isset($_SESSION["user_id"])) {
    echo "<p>Please log in first.</p>";
    exit;
}

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

if ($shopId <= 0) {
    echo "<p>Invalid shop selected.</p>";
    exit;
}

/*
|--------------------------------------------------------------------------
| GET SHOP
|--------------------------------------------------------------------------
*/
$shop = null;
$shopStmt = $conn->prepare("
    SELECT id, shop_name, shop_type
    FROM users
    WHERE id = ?
    LIMIT 1
");
$shopStmt->bind_param("i", $shopId);
$shopStmt->execute();
$shopResult = $shopStmt->get_result();
$shop = $shopResult->fetch_assoc();

if (!$shop) {
    echo "<p>Shop not found.</p>";
    exit;
}

/*
|--------------------------------------------------------------------------
| INIT SESSION ARRAYS
|--------------------------------------------------------------------------
*/
if (!isset($_SESSION['order_items']) || !is_array($_SESSION['order_items'])) {
    $_SESSION['order_items'] = [];
}

/*
|--------------------------------------------------------------------------
| HANDLE FORM ACTIONS
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Shared fields
    $_SESSION['order_due_date'] = trim($_POST['due_date'] ?? '');
    $_SESSION['order_notes'] = trim($_POST['notes'] ?? '');

    // Optional reference file upload
    if (!empty($_FILES['reference_file']['name'])) {
        $uploadDir = "../uploads/order_references/";

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

        $fileName = time() . "_" . preg_replace('/[^A-Za-z0-9._-]/', '_', basename($_FILES['reference_file']['name']));
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES['reference_file']['tmp_name'], $targetPath)) {
            $_SESSION['order_reference_file'] = $fileName;
        }
    }

    // ADD ITEM
    if (isset($_POST['add_item'])) {
        $serviceType = trim($_POST['service_type'] ?? '');
        $subType = trim($_POST['sub_type'] ?? '');
        $size = trim($_POST['size'] ?? '');
        $quantity = (int)($_POST['quantity'] ?? 0);

        if ($serviceType === '' || $subType === '' || $quantity <= 0) {
            echo "<script>alert('Please complete service type, sub type, and quantity.');</script>";
        } else {
            // Require size only for jersey
            if (strtolower($serviceType) === 'jersey' && $size === '') {
                echo "<script>alert('Please select a size for jersey orders.');</script>";
            } else {
                $_SESSION['order_items'][] = [
                    'service_type' => $serviceType,
                    'service_name' => $subType,
                    'size' => $size,
                    'quantity' => $quantity
                ];

                echo "<script>window.location='customer.php?page=customer-order-now&shop_id=" . $shopId . "';</script>";
exit;
                exit;
            }
        }
    }

    // REMOVE ITEM
    if (isset($_POST['remove_item'])) {
        $removeIndex = (int)($_POST['remove_index'] ?? -1);

        if (isset($_SESSION['order_items'][$removeIndex])) {
            unset($_SESSION['order_items'][$removeIndex]);
            $_SESSION['order_items'] = array_values($_SESSION['order_items']);
        }

        header("Location: customer.php?page=customer-order-now&shop_id=" . $shopId);
        exit;
    }

    // OPTIONAL CLEAR ALL
    if (isset($_POST['clear_all_items'])) {
        $_SESSION['order_items'] = [];
        header("Location: customer.php?page=customer-order-now&shop_id=" . $shopId);
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| GET SERVICE TYPES FOR THIS SHOP
|--------------------------------------------------------------------------
*/
$serviceTypes = [];
$typeStmt = $conn->prepare("
    SELECT DISTINCT service_type
    FROM services
    WHERE owner_shop_id = ?
      AND status = 'active'
    ORDER BY service_type ASC
");
$typeStmt->bind_param("i", $shopId);
$typeStmt->execute();
$typeResult = $typeStmt->get_result();

while ($row = $typeResult->fetch_assoc()) {
    $serviceTypes[] = $row['service_type'];
}

/*
|--------------------------------------------------------------------------
| GET SUB TYPES FOR THIS SHOP
|--------------------------------------------------------------------------
*/
$subTypeMap = [];

$subStmt = $conn->prepare("
    SELECT DISTINCT service_type, service_name
    FROM services
    WHERE owner_shop_id = ?
      AND status = 'active'
    ORDER BY service_type ASC, service_name ASC
");
$subStmt->bind_param("i", $shopId);
$subStmt->execute();
$subResult = $subStmt->get_result();

while ($row = $subResult->fetch_assoc()) {
    $type = $row['service_type'];
    $name = $row['service_name'];

    if (!isset($subTypeMap[$type])) {
        $subTypeMap[$type] = [];
    }

    $subTypeMap[$type][] = $name;
}

$orderItems = $_SESSION['order_items'] ?? [];
$totalItems = 0;

foreach ($orderItems as $item) {
    $totalItems += (int)($item['quantity'] ?? 0);
}

$dueDateValue = $_SESSION['order_due_date'] ?? '';
$notesValue = $_SESSION['order_notes'] ?? '';
?>

<div class="create-order-page">
    <div class="create-order-header">
        <h1>Create Order</h1>
        <p>Place your order for <?php echo htmlspecialchars($shop["shop_name"] ?? "this shop"); ?></p>
    </div>

    <div class="create-order-layout">
        <!-- LEFT: MAIN FORM -->
        <div class="create-order-main">
            <div class="create-order-card">
                <div class="order-shop-summary">
                    <h2><?php echo htmlspecialchars($shop["shop_name"] ?? "Unnamed Shop"); ?></h2>
                    <p><strong>Shop Type:</strong> <?php echo htmlspecialchars($shop["shop_type"] ?? "Not specified"); ?></p>
                </div>

                <form class="create-order-form"
                      action="customer.php?page=customer-order-now&shop_id=<?php echo $shopId; ?>"
                      method="POST"
                      enctype="multipart/form-data">

                    <input type="hidden" name="shop_id" value="<?php echo (int)$shopId; ?>">

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="service_type">Service Type</label>
                            <select name="service_type" id="service_type" required>
                                <option value="">Select Service Type</option>
                                <?php foreach ($serviceTypes as $type): ?>
                                    <option value="<?php echo htmlspecialchars($type); ?>">
                                        <?php echo htmlspecialchars(ucfirst($type)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="sub_type">Sub Type</label>
                            <select name="sub_type" id="sub_type" required>
                                <option value="">Select Sub Type</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="quantity">Quantity</label>
                            <input type="number" name="quantity" id="quantity" min="1" value="1" required>
                        </div>

                        <div class="form-group full" id="size-group" style="display:none;">
    <label id="size-label">Size</label>
    <div class="jersey-size-options" id="size-options"></div>
</div>

                        <div class="form-group">
                            <label for="due_date">Due Date</label>
                            <input type="date" name="due_date" id="due_date" value="<?php echo htmlspecialchars($dueDateValue); ?>">
                        </div>

                        <div class="form-group">
                            <label for="reference_file">Design / Reference File</label>
                            <input type="file" name="reference_file" id="reference_file">
                        </div>

                        <div class="form-group full">
                            <label for="notes">Notes / Custom Instructions</label>
                            <textarea name="notes" id="notes" rows="5" placeholder="Enter instructions for your order"><?php echo htmlspecialchars($notesValue); ?></textarea>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="submit" name="add_item" class="btn-primary">Add Item</button>
                        <a href="customer.php?page=shop_view-details&id=<?php echo $shopId; ?>" class="btn-secondary">Cancel</a>
                    </div>
                </form>
            </div>
        </div>

        <!-- RIGHT: CURRENT ORDER ITEMS -->
        <div class="create-order-side">
            <div class="order-items-card">
                <div class="order-items-head">
                    <h3>Current Order Items</h3>
                    <?php if (!empty($orderItems)): ?>
                        <form method="POST" action="customer.php?page=customer-order-now&shop_id=<?php echo $shopId; ?>">
                            <button type="submit" name="clear_all_items" class="clear-all-btn">Clear All</button>
                        </form>
                    <?php endif; ?>
                </div>

                <?php if (!empty($orderItems)): ?>
                    <div class="order-items-list">
                        <?php foreach ($orderItems as $index => $item): ?>
                            <div class="order-item-row">
                                <div class="order-item-title">
                                    <?php echo htmlspecialchars($item['service_type']); ?>
                                </div>

                                <div class="order-item-meta">
                                    <?php echo htmlspecialchars($item['service_name']); ?>
                                    <?php if (!empty($item['size'])): ?>
                                        <span class="item-size">(Size <?php echo htmlspecialchars($item['size']); ?>)</span>
                                    <?php endif; ?>
                                </div>

                                <div class="order-item-bottom">
                                    <span class="item-qty">Qty: <?php echo (int)$item['quantity']; ?></span>

                                    <form method="POST" action="customer.php?page=customer-order-now&shop_id=<?php echo $shopId; ?>">
                                        <input type="hidden" name="remove_index" value="<?php echo $index; ?>">
                                        <button type="submit" name="remove_item" class="remove-btn">Remove</button>
                                    </form>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="order-items-total">
                        Total Items: <?php echo (int)$totalItems; ?>
                    </div>

                   <form id="summaryForm" action="customer.php?page=customer-order-summary" method="POST" class="summary-form">
    <input type="hidden" name="shop_id" value="<?php echo (int)$shopId; ?>">
    <input type="hidden" name="due_date" value="<?php echo htmlspecialchars($dueDateValue); ?>">
    <input type="hidden" name="notes" value="<?php echo htmlspecialchars($notesValue); ?>">

    <?php foreach ($orderItems as $item): ?>
        <input type="hidden" name="service_type[]" value="<?php echo htmlspecialchars($item['service_type']); ?>">
        <input type="hidden" name="service_name[]" value="<?php echo htmlspecialchars($item['service_name']); ?>">
        <input type="hidden" name="size[]" value="<?php echo htmlspecialchars($item['size'] ?? ''); ?>">
        <input type="hidden" name="quantity[]" value="<?php echo (int)$item['quantity']; ?>">
    <?php endforeach; ?>

    <button type="submit" class="btn-primary summary-btn">
        Proceed to Order Summary
    </button>
</form>
                <?php else: ?>
                    <div class="empty-order-box">
                        <p>No items added yet.</p>
                        <small>Add items first, then proceed to order summary.</small>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
.create-order-layout {
     display: grid;
    grid-template-columns: minmax(800px, 1fr) 420px;
    gap: 24px;
    max-width: 1900px;
   
}

.create-order-main,
.create-order-side {
    min-width: 0;
}

.order-items-card {
    background: #fff;
    border-radius: 18px;
    padding: 18px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.06);
    position: sticky;
    top: 20px;
}

.order-items-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    margin-bottom: 14px;
}

.order-items-head h3 {
    margin: 0;
    font-size: 22px;
    font-weight: 700;
}

.clear-all-btn {
    border: none;
    background: transparent;
    color: #d93025;
    font-size: 13px;
    cursor: pointer;
    font-weight: 600;
}

.order-items-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.order-item-row {
    border: 1px solid #ececec;
    border-radius: 12px;
    padding: 12px;
    background: #fafafa;
}

.order-item-title {
    font-size: 15px;
    font-weight: 700;
    color: #222;
    margin-bottom: 4px;
    text-transform: capitalize;
}

.order-item-meta {
    font-size: 14px;
    color: #444;
    line-height: 1.4;
    margin-bottom: 8px;
}

.item-size {
    color: #666;
}

.order-item-bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.item-qty {
    font-size: 13px;
    font-weight: 600;
    color: #222;
}

.remove-btn {
    border: none;
    background: transparent;
    color: #d93025;
    font-size: 13px;
    cursor: pointer;
    font-weight: 600;
    padding: 0;
}

.order-items-total {
    margin-top: 14px;
    padding-top: 12px;
    border-top: 1px solid #e3e3e3;
    font-size: 16px;
    font-weight: 700;
    color: #222;
}

.summary-form {
    margin-top: 14px;
}

.summary-btn {
    width: 100%;
}

.empty-order-box {
    border: 1px dashed #d6d6d6;
    border-radius: 12px;
    padding: 18px;
    text-align: center;
    color: #666;
    background: #fafafa;
}

.empty-order-box p {
    margin: 0 0 6px;
    font-weight: 600;
}

.jersey-size-options {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    margin-top: 8px;
}

.jersey-size-box {
    position: relative;
    display: inline-block;
    cursor: pointer;
}

.jersey-size-box input[type="radio"] {
    display: none;
}

.jersey-size-box span {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 70px;
    height: 34px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    background: #fff;
    color: #777;
    font-size: 15px;
    font-weight: 600;
    transition: all 0.2s ease;
}

.jersey-size-box input[type="radio"]:checked + span {
    border: 2px solid #16a7e3;
    color: #16a7e3;
    background: #fff;
}

.jersey-size-box input[type="radio"]:checked + span::after {
    content: "";
    position: absolute;
    right: 0;
    bottom: 0;
    width: 0;
    height: 0;
    border-left: 14px solid transparent;
    border-top: 14px solid transparent;
    border-right: 14px solid #16a7e3;
    border-bottom: 14px solid #16a7e3;
    border-bottom-right-radius: 6px;
}

.jersey-size-box input[type="radio"]:checked + span::before {
    content: "✓";
    position: absolute;
    right: 3px;
    bottom: 1px;
    color: #fff;
    font-size: 10px;
    font-weight: bold;
    z-index: 2;
}

@media (max-width: 1200px) {
    .create-order-layout {
        grid-template-columns: 1fr;
    }

    .order-items-card {
        position: static;
    }
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const serviceTypeSelect = document.getElementById("service_type");
    const subTypeSelect = document.getElementById("sub_type");
    const sizeGroup = document.getElementById("size-group");
    const sizeLabel = document.getElementById("size-label");
    const sizeOptions = document.getElementById("size-options");

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

    const sizeConfig = {
        jersey: {
            label: "Size",
            options: ["S", "M", "L", "XL"]
        },
        mug: {
            label: "Mug Size",
            options: ["11 oz", "15 oz"]
        },
        tarpaulin: {
            label: "Tarpaulin Size",
            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 populateSubTypes(selectedType) {
        subTypeSelect.innerHTML = '<option value="">Select Sub Type</option>';

        const matchedKey = Object.keys(subTypeMap).find(function (key) {
            return normalizeText(key) === normalizeText(selectedType);
        });

        if (!matchedKey || !subTypeMap[matchedKey]) return;

        subTypeMap[matchedKey].forEach(function (name) {
            const option = document.createElement("option");
            option.value = name;
            option.textContent = name;
            subTypeSelect.appendChild(option);
        });
    }

    function renderSizeOptions(selectedType) {
        sizeOptions.innerHTML = "";

        const normalizedType = normalizeText(selectedType);

        if (!sizeConfig[normalizedType]) {
            sizeGroup.style.display = "none";
            return;
        }

        sizeLabel.textContent = sizeConfig[normalizedType].label;

        sizeConfig[normalizedType].options.forEach(function (size) {
            const label = document.createElement("label");
            label.className = "jersey-size-box";

            label.innerHTML = `
                <input type="radio" name="size" value="${size}">
                <span>${size}</span>
            `;

            sizeOptions.appendChild(label);
        });

        sizeGroup.style.display = "block";
    }

    function handleServiceTypeChange() {
        const selectedType = serviceTypeSelect.value;
        populateSubTypes(selectedType);
        renderSizeOptions(selectedType);
    }

    serviceTypeSelect.addEventListener("change", handleServiceTypeChange);

    handleServiceTypeChange();
});
</script>