<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

// Get pre-selected customer if any
$selected_customer_id = isset($_GET['customer']) ? (int)$_GET['customer'] : 0;

// Fetch customers for dropdown
$customers_sql = "SELECT customer_id, customer_code, first_name, last_name, phone, customer_type 
                  FROM customers WHERE status = 'ACTIVE' ORDER BY first_name, last_name";
$customers_result = $conn->query($customers_sql);

// Fetch services grouped by category
$services_sql = "SELECT s.*, sc.category_name 
                 FROM services s 
                 LEFT JOIN service_categories sc ON s.category_id = sc.category_id 
                 WHERE s.is_active = 1 
                 ORDER BY sc.sort_order, sc.category_name, s.sort_order, s.service_name";
$services_result = $conn->query($services_sql);

$services_by_category = [];
while ($service = $services_result->fetch_assoc()) {
    $category = $service['category_name'] ?: 'Other Services';
    $services_by_category[$category][] = $service;
}

$success_message = '';
$error_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $customer_id = (int)$_POST['customer_id'];
    $pickup_date = $_POST['pickup_date'];
    $delivery_date = $_POST['delivery_date'];
    $priority = $_POST['priority'];
    $special_instructions = trim($_POST['special_instructions']);
    $customer_notes = trim($_POST['customer_notes']);
    $services = isset($_POST['services']) ? $_POST['services'] : [];
    $quantities = isset($_POST['quantities']) ? $_POST['quantities'] : [];
    $notes = isset($_POST['service_notes']) ? $_POST['service_notes'] : [];
    
    // Validation
    if (empty($customer_id) || empty($services)) {
        $error_message = "Please select a customer and at least one service.";
    } else {
        $conn->begin_transaction();
        
        try {
            // Calculate estimated delivery if not provided
            if (empty($delivery_date)) {
                $delivery_date = date('Y-m-d', strtotime('+2 days'));
            }
            
            // Insert order
            $insert_order_sql = "INSERT INTO orders (customer_id, pickup_date, delivery_date, 
                                status, priority, special_instructions, customer_notes, 
                                created_by, assigned_to) 
                                VALUES (?, ?, ?, 'PENDING', ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_order_sql);
            $stmt->bind_param("isssssii", $customer_id, $pickup_date, $delivery_date, 
                             $priority, $special_instructions, $customer_notes, $user_id, $user_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Error creating order");
            }
            
            $order_id = $conn->insert_id;
            
            // Insert order items
            $total_pieces = 0;
            $subtotal = 0;
            
            foreach ($services as $index => $service_id) {
                $quantity = (int)($quantities[$index] ?? 1);
                $service_notes = trim($notes[$index] ?? '');
                
                if ($quantity > 0) {
                    // Get service details
                    $service_sql = "SELECT price FROM services WHERE service_id = ?";
                    $service_stmt = $conn->prepare($service_sql);
                    $service_stmt->bind_param("i", $service_id);
                    $service_stmt->execute();
                    $service_data = $service_stmt->get_result()->fetch_assoc();
                    
                    $unit_price = $service_data['price'];
                    $total_price = $unit_price * $quantity;
                    
                    // Insert order item
                    $item_sql = "INSERT INTO order_items (order_id, service_id, quantity, 
                                unit_price, total_price, notes) 
                                VALUES (?, ?, ?, ?, ?, ?)";
                    $item_stmt = $conn->prepare($item_sql);
                    $item_stmt->bind_param("iiidds", $order_id, $service_id, $quantity, 
                                          $unit_price, $total_price, $service_notes);
                    
                    if (!$item_stmt->execute()) {
                        throw new Exception("Error adding order item");
                    }
                    
                    $total_pieces += $quantity;
                    $subtotal += $total_price;
                }
            }
            
            // Update order totals
            $update_totals_sql = "UPDATE orders SET total_pieces = ?, subtotal = ?, 
                                 total_amount = ?, balance_amount = ? WHERE order_id = ?";
            $update_stmt = $conn->prepare($update_totals_sql);
            $update_stmt->bind_param("idddi", $total_pieces, $subtotal, $subtotal, $subtotal, $order_id);
            
            if (!$update_stmt->execute()) {
                throw new Exception("Error updating order totals");
            }
            
            // Get the generated order number
            $order_number_sql = "SELECT order_number FROM orders WHERE order_id = ?";
            $order_stmt = $conn->prepare($order_number_sql);
            $order_stmt->bind_param("i", $order_id);
            $order_stmt->execute();
            $order_data = $order_stmt->get_result()->fetch_assoc();
            
            $conn->commit();
            
            $success_message = "Order created successfully! Order Number: " . $order_data['order_number'];
            
            // Clear form data after successful submission
            $_POST = array();
            $selected_customer_id = 0;
            
        } catch (Exception $e) {
            $conn->rollback();
            $error_message = "Error creating order: " . $e->getMessage();
        }
    }
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'New Order - Laundry Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .form-section {
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .form-label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
            display: block;
        }
        
        .form-control {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            width: 100%;
            transition: all 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .service-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            display: none;
            transition: all 0.3s ease;
        }
        
        .service-item.active {
            display: block;
        }
        
        .service-item.selected {
            background: #eff6ff;
            border-color: #3b82f6;
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
        }
        
        .service-checkbox {
            margin-right: 0.75rem;
            transform: scale(1.1);
        }
        
        .service-header {
            display: flex;
            align-items: flex-start;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .service-main-info {
            flex: 1;
        }
        
        .service-name {
            font-weight: 600;
            color: #1e293b;
            font-size: 1rem;
            margin-bottom: 0.25rem;
        }
        
        .service-price {
            color: #059669;
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .service-description {
            color: #64748b;
            font-size: 0.8rem;
            margin-top: 0.25rem;
        }
        
        .service-details {
            display: none;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1rem;
            animation: slideDown 0.3s ease-out;
        }
        
        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .service-details.active {
            display: block;
        }
        
        .service-config-grid {
            display: grid;
            grid-template-columns: 2fr 120px 150px 2fr;
            gap: 1.5rem;
            align-items: start;
        }
        
        .selected-service-info {
            background: #f0f9ff;
            border: 1px solid #bae6fd;
            border-radius: 6px;
            padding: 1rem;
        }
        
        .selected-service-name {
            font-weight: 600;
            color: #1e40af;
            font-size: 0.95rem;
            margin-bottom: 0.5rem;
        }
        
        .selected-service-price {
            color: #059669;
            font-weight: 500;
            font-size: 0.85rem;
        }
        
        .line-total-display {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            border-radius: 6px;
            padding: 0.75rem;
            text-align: center;
        }
        
        .line-total-amount {
            font-weight: 600;
            color: #059669;
            font-size: 1.1rem;
        }
        
        .category-header {
            background: #3b82f6;
            color: white;
            padding: 0.75rem 1rem;
            margin: 1.5rem 0 1rem 0;
            border-radius: 8px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .customer-info {
            background: #f0f9ff;
            border: 1px solid #bae6fd;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
        }
        
        .order-summary {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            position: sticky;
            top: 2rem;
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .summary-row:last-child {
            border-bottom: none;
            font-weight: 600;
            font-size: 1.125rem;
            margin-top: 0.5rem;
            padding-top: 1rem;
            border-top: 2px solid #e2e8f0;
        }
        
        .selected-services-list {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            max-height: 200px;
            overflow-y: auto;
        }
        
        .selected-service-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .selected-service-item:last-child {
            border-bottom: none;
        }
        
        .service-item-name {
            font-weight: 500;
            color: #374151;
        }
        
        .service-item-details {
            color: #64748b;
            font-size: 0.85rem;
        }
        
        .btn-primary {
            background: #3b82f6;
            border: 1px solid #3b82f6;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-block;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            border-color: #1d4ed8;
            color: white;
        }
        
        .btn-secondary {
            background: #6b7280;
            border: 1px solid #6b7280;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-block;
            transition: all 0.2s ease;
        }
        
        .btn-secondary:hover {
            background: #4b5563;
            border-color: #4b5563;
            color: white;
        }
        
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        
        .alert-success {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            color: #166534;
        }
        
        .alert-danger {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #991b1b;
        }
        
        .required {
            color: #ef4444;
        }
        
        .search-box {
            margin-bottom: 1rem;
        }
        
        .search-box input {
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem 1rem;
            font-size: 0.9rem;
            width: 100%;
            transition: all 0.2s ease;
        }
        
        .search-box input:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .row {
            display: flex;
            flex-wrap: wrap;
            margin-left: -0.75rem;
            margin-right: -0.75rem;
        }
        
        .col-md-6 {
            flex: 0 0 100%;
            max-width: 100%;
            padding-left: 0.75rem;
            padding-right: 0.75rem;
        }
        
        .col-md-8 {
            flex: 0 0 100%;
            max-width: 100%;
            padding-left: 0.75rem;
            padding-right: 0.75rem;
        }
        
        .col-md-4 {
            flex: 0 0 100%;
            max-width: 100%;
            padding-left: 0.75rem;
            padding-right: 0.75rem;
        }
        
        @media (min-width: 768px) {
            .col-md-6 {
                flex: 0 0 50%;
                max-width: 50%;
            }
            
            .col-md-8 {
                flex: 0 0 66.666667%;
                max-width: 66.666667%;
            }
            
            .col-md-4 {
                flex: 0 0 33.333333%;
                max-width: 33.333333%;
            }
        }
        
        .mb-3 { margin-bottom: 1rem; }
        .d-flex { display: flex; }
        .justify-content-between { justify-content: space-between; }
        .align-items-center { align-items: center; }
        .me-2 { margin-right: 0.5rem; }
        .ms-2 { margin-left: 0.5rem; }
        .text-muted { color: #64748b; }
        .fw-bold { font-weight: 600; }
        .mt-2 { margin-top: 0.5rem; }
        .mt-4 { margin-top: 1rem; }
        .mb-4 { margin-bottom: 1rem; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div>
                            <h4 class="mb-0">Create New Order</h4>
                            <p class="text-muted mb-0">Process a new laundry order</p>
                        </div>
                        <a href="all_orders.php" class="btn-secondary">
                            <i class="ph-list me-2"></i>View All Orders
                        </a>
                    </div>

                    <?php if ($success_message): ?>
                    <div class="alert alert-success">
                        <strong>Success!</strong> <?php echo $success_message; ?>
                        <div class="mt-2">
                            <a href="new_order.php" class="btn-secondary">Create Another Order</a>
                            <a href="all_orders.php" class="btn-primary ms-2">View Orders</a>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($error_message): ?>
                    <div class="alert alert-danger">
                        <strong>Error!</strong> <?php echo $error_message; ?>
                    </div>
                    <?php endif; ?>

                    <form method="POST" action="new_order.php" id="orderForm">
                        <div class="row">
                            <div class="col-md-8">
                                <!-- Customer Information -->
                                <div class="form-card">
                                    <div class="form-section">
                                        <h5 class="section-title">Customer Information</h5>
                                        
                                        <div class="mb-3">
                                            <label for="customer_id" class="form-label">
                                                Select Customer <span class="required">*</span>
                                            </label>
                                            <select class="form-control" id="customer_id" name="customer_id" required>
                                                <option value="">Choose a customer...</option>
                                                <?php 
                                                $customers_result->data_seek(0);
                                                while ($customer = $customers_result->fetch_assoc()): 
                                                ?>
                                                <option value="<?php echo $customer['customer_id']; ?>" 
                                                        <?php echo ($customer['customer_id'] == $selected_customer_id) ? 'selected' : ''; ?>
                                                        data-phone="<?php echo htmlspecialchars($customer['phone']); ?>"
                                                        data-type="<?php echo htmlspecialchars($customer['customer_type']); ?>">
                                                    <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?> 
                                                    (<?php echo htmlspecialchars($customer['customer_code']); ?>)
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div id="customerInfo" class="customer-info" style="display: none;">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <strong>Phone:</strong> <span id="customerPhone"></span>
                                                </div>
                                                <div class="col-md-6">
                                                    <strong>Type:</strong> <span id="customerType"></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Order Details -->
                                <div class="form-card">
                                    <div class="form-section">
                                        <h5 class="section-title">Order Details</h5>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="pickup_date" class="form-label">Pickup Date</label>
                                                    <input type="date" class="form-control" id="pickup_date" name="pickup_date" 
                                                           value="<?php echo date('Y-m-d'); ?>" min="<?php echo date('Y-m-d'); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="delivery_date" class="form-label">Delivery Date</label>
                                                    <input type="date" class="form-control" id="delivery_date" name="delivery_date" 
                                                           value="<?php echo date('Y-m-d', strtotime('+2 days')); ?>" 
                                                           min="<?php echo date('Y-m-d', strtotime('+1 day')); ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="priority" class="form-label">Priority</label>
                                            <select class="form-control" id="priority" name="priority">
                                                <option value="NORMAL">Normal</option>
                                                <option value="HIGH">High Priority</option>
                                                <option value="URGENT">Urgent</option>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="special_instructions" class="form-label">Special Instructions</label>
                                            <textarea class="form-control" id="special_instructions" name="special_instructions" 
                                                      rows="3" placeholder="Any special handling instructions..."></textarea>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="customer_notes" class="form-label">Customer Notes</label>
                                            <textarea class="form-control" id="customer_notes" name="customer_notes" 
                                                      rows="2" placeholder="Notes from customer..."></textarea>
                                        </div>
                                    </div>
                                </div>

                                <!-- Services Selection -->
                                <div class="form-card">
                                    <div class="form-section">
                                        <h5 class="section-title">Select Services</h5>
                                        
                                        <div class="search-box">
                                            <input type="text" placeholder="🔍 Search services..." 
                                                   oninput="filterServices(this.value)" id="serviceSearch">
                                        </div>
                                        
                                        <div id="servicesContainer">
                                            <?php foreach ($services_by_category as $category => $services): ?>
                                            <div class="category-header">
                                                <i class="ph-tag"></i>
                                                <?php echo htmlspecialchars($category); ?>
                                            </div>
                                            
                                            <?php foreach ($services as $service): ?>
                                            <div class="service-item" id="service-<?php echo $service['service_id']; ?>">
                                                <div class="service-header">
                                                    <input type="checkbox" class="service-checkbox" 
                                                           name="services[]" value="<?php echo $service['service_id']; ?>"
                                                           onchange="toggleServiceDetails(<?php echo $service['service_id']; ?>)">
                                                    
                                                    <div class="service-main-info">
                                                        <div class="service-name"><?php echo htmlspecialchars($service['service_name']); ?></div>
                                                        <div class="service-price">KSh <?php echo number_format($service['price']); ?> per <?php echo $service['unit']; ?></div>
                                                        <?php if ($service['description']): ?>
                                                        <div class="service-description"><?php echo htmlspecialchars($service['description']); ?></div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                
                                                <div class="service-details" id="details-<?php echo $service['service_id']; ?>">
                                                    <div class="service-config-grid">
                                                        <div>
                                                            <label class="form-label">Selected Service</label>
                                                            <div class="selected-service-info">
                                                                <div class="selected-service-name"><?php echo htmlspecialchars($service['service_name']); ?></div>
                                                                <div class="selected-service-price">KSh <?php echo number_format($service['price']); ?> per <?php echo $service['unit']; ?></div>
                                                            </div>
                                                        </div>
                                                        
                                                        <div>
                                                            <label class="form-label">Quantity</label>
                                                            <input type="number" class="form-control quantity-input" 
                                                                   name="quantities[]" min="1" value="1"
                                                                   data-price="<?php echo $service['price']; ?>"
                                                                   data-service-name="<?php echo htmlspecialchars($service['service_name']); ?>"
                                                                   onchange="updateSummary()">
                                                        </div>
                                                        
                                                        <div>
                                                            <label class="form-label">Line Total</label>
                                                            <div class="line-total-display">
                                                                <div class="line-total-amount">KSh <?php echo number_format($service['price']); ?></div>
                                                            </div>
                                                        </div>
                                                        
                                                        <div>
                                                            <label class="form-label">Special Notes</label>
                                                            <input type="text" class="form-control" name="service_notes[]" 
                                                                   placeholder="Any special instructions...">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endforeach; ?>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <!-- Order Summary -->
                                <div class="order-summary">
                                    <h5 class="mb-3">Order Summary</h5>
                                    
                                    <div id="selectedServicesList" class="selected-services-list" style="display: none;">
                                        <h6 style="margin-bottom: 1rem; color: #374151; font-size: 0.9rem; font-weight: 600;">Selected Services:</h6>
                                        <div id="selectedServicesContent"></div>
                                    </div>
                                    
                                    <div class="summary-row">
                                        <span>Total Items:</span>
                                        <span id="totalItems">0</span>
                                    </div>
                                    
                                    <div class="summary-row">
                                        <span>Subtotal:</span>
                                        <span id="subtotal">KSh 0.00</span>
                                    </div>
                                    
                                    <div class="summary-row">
                                        <span>Total Amount:</span>
                                        <span id="totalAmount">KSh 0.00</span>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between mt-4">
                                        <a href="all_orders.php" class="btn-secondary">Cancel</a>
                                        <button type="submit" class="btn-primary">Create Order</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        // Show customer info when selected
        document.getElementById('customer_id').addEventListener('change', function() {
            const option = this.options[this.selectedIndex];
            const customerInfo = document.getElementById('customerInfo');
            
            if (this.value) {
                document.getElementById('customerPhone').textContent = option.dataset.phone;
                document.getElementById('customerType').textContent = option.dataset.type;
                customerInfo.style.display = 'block';
            } else {
                customerInfo.style.display = 'none';
            }
        });

        // Toggle service details
        function toggleServiceDetails(serviceId) {
            const checkbox = document.querySelector(`input[value="${serviceId}"]`);
            const details = document.getElementById(`details-${serviceId}`);
            const serviceItem = document.getElementById(`service-${serviceId}`);
            
            if (checkbox.checked) {
                details.classList.add('active');
                serviceItem.classList.add('selected');
            } else {
                details.classList.remove('active');
                serviceItem.classList.remove('selected');
            }
            
            updateSummary();
        }

        // Update order summary
        function updateSummary() {
            let totalItems = 0;
            let subtotal = 0;
            let selectedServices = [];
            
            document.querySelectorAll('input[name="services[]"]:checked').forEach(function(checkbox) {
                const serviceId = checkbox.value;
                const quantityInput = document.querySelector(`#details-${serviceId} .quantity-input`);
                const lineTotalDisplay = document.querySelector(`#details-${serviceId} .line-total-amount`);
                
                if (quantityInput) {
                    const quantity = parseInt(quantityInput.value) || 1;
                    const price = parseFloat(quantityInput.dataset.price) || 0;
                    const serviceName = quantityInput.dataset.serviceName || 'Unknown Service';
                    const total = quantity * price;
                    
                    totalItems += quantity;
                    subtotal += total;
                    
                    // Update line total display
                    lineTotalDisplay.textContent = `KSh ${total.toLocaleString('en-KE', {minimumFractionDigits: 2})}`;
                    
                    // Add to selected services list
                    selectedServices.push({
                        name: serviceName,
                        quantity: quantity,
                        unitPrice: price,
                        total: total
                    });
                }
            });
            
            // Update summary totals
            document.getElementById('totalItems').textContent = totalItems;
            document.getElementById('subtotal').textContent = `KSh ${subtotal.toLocaleString('en-KE', {minimumFractionDigits: 2})}`;
            document.getElementById('totalAmount').textContent = `KSh ${subtotal.toLocaleString('en-KE', {minimumFractionDigits: 2})}`;
            
            // Update selected services list
            updateSelectedServicesList(selectedServices);
        }
        
        // Update selected services list in summary
        function updateSelectedServicesList(services) {
            const listContainer = document.getElementById('selectedServicesList');
            const contentContainer = document.getElementById('selectedServicesContent');
            
            if (services.length === 0) {
                listContainer.style.display = 'none';
                return;
            }
            
            listContainer.style.display = 'block';
            
            let content = '';
            services.forEach(function(service) {
                content += `
                    <div class="selected-service-item">
                        <div>
                            <div class="service-item-name">${service.name}</div>
                            <div class="service-item-details">${service.quantity} × KSh ${service.unitPrice.toLocaleString('en-KE', {minimumFractionDigits: 2})}</div>
                        </div>
                        <div class="fw-bold">KSh ${service.total.toLocaleString('en-KE', {minimumFractionDigits: 2})}</div>
                    </div>
                `;
            });
            
            contentContainer.innerHTML = content;
        }

        // Filter services based on search
        function filterServices(searchTerm) {
            const services = document.querySelectorAll('.service-item');
            const categories = document.querySelectorAll('.category-header');
            searchTerm = searchTerm.toLowerCase();
            
            let visibleCategories = new Set();
            
            services.forEach(function(service) {
                const serviceName = service.querySelector('.service-name').textContent.toLowerCase();
                const serviceDescription = service.querySelector('.service-description');
                const descriptionText = serviceDescription ? serviceDescription.textContent.toLowerCase() : '';
                
                if (serviceName.includes(searchTerm) || descriptionText.includes(searchTerm)) {
                    service.style.display = 'block';
                    // Find the category this service belongs to
                    let currentElement = service;
                    while (currentElement.previousElementSibling) {
                        currentElement = currentElement.previousElementSibling;
                        if (currentElement.classList.contains('category-header')) {
                            visibleCategories.add(currentElement);
                            break;
                        }
                    }
                } else {
                    service.style.display = 'none';
                }
            });
            
            // Show/hide categories based on whether they have visible services
            categories.forEach(function(category) {
                if (searchTerm === '' || visibleCategories.has(category)) {
                    category.style.display = 'flex';
                } else {
                    category.style.display = 'none';
                }
            });
        }

        // Auto-update delivery date when pickup date changes
        document.getElementById('pickup_date').addEventListener('change', function() {
            const pickupDate = new Date(this.value);
            const deliveryDate = new Date(pickupDate);
            deliveryDate.setDate(deliveryDate.getDate() + 2);
            
            document.getElementById('delivery_date').value = deliveryDate.toISOString().split('T')[0];
        });

        // Form validation
        document.getElementById('orderForm').addEventListener('submit', function(e) {
            const customerId = document.getElementById('customer_id').value;
            const checkedServices = document.querySelectorAll('input[name="services[]"]:checked');
            
            if (!customerId) {
                e.preventDefault();
                alert('Please select a customer.');
                document.getElementById('customer_id').focus();
                return false;
            }
            
            if (checkedServices.length === 0) {
                e.preventDefault();
                alert('Please select at least one service.');
                document.getElementById('serviceSearch').focus();
                return false;
            }
            
            // Validate quantities
            let validQuantities = true;
            let invalidService = null;
            
            checkedServices.forEach(function(checkbox) {
                const serviceId = checkbox.value;
                const quantityInput = document.querySelector(`#details-${serviceId} .quantity-input`);
                const quantity = parseInt(quantityInput.value) || 0;
                
                if (quantity < 1) {
                    validQuantities = false;
                    invalidService = quantityInput;
                }
            });
            
            if (!validQuantities) {
                e.preventDefault();
                alert('Please enter valid quantities (minimum 1) for all selected services.');
                if (invalidService) {
                    invalidService.focus();
                    invalidService.select();
                }
                return false;
            }
            
            // Show loading state
            const submitButton = this.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            submitButton.textContent = 'Creating Order...';
            submitButton.disabled = true;
            
            // Re-enable button after 10 seconds as fallback
            setTimeout(() => {
                submitButton.textContent = originalText;
                submitButton.disabled = false;
            }, 10000);
        });

        // Initialize page
        document.addEventListener('DOMContentLoaded', function() {
            // Show all services initially
            document.querySelectorAll('.service-item').forEach(function(item) {
                item.classList.add('active');
            });
            
            // Trigger customer info display if pre-selected
            const customerSelect = document.getElementById('customer_id');
            if (customerSelect.value) {
                customerSelect.dispatchEvent(new Event('change'));
            }
            
            // Set minimum dates
            const today = new Date().toISOString().split('T')[0];
            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            const tomorrowStr = tomorrow.toISOString().split('T')[0];
            
            document.getElementById('pickup_date').min = today;
            document.getElementById('delivery_date').min = tomorrowStr;
            
            // Initialize summary
            updateSummary();
        });

        // Clear success message after 10 seconds
        <?php if ($success_message): ?>
        setTimeout(function() {
            const alert = document.querySelector('.alert-success');
            if (alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 500);
            }
        }, 10000);
        <?php endif; ?>

        // Enhanced keyboard navigation
        document.addEventListener('keydown', function(e) {
            // Press Ctrl+F to focus on service search
            if (e.ctrlKey && e.key === 'f') {
                e.preventDefault();
                document.getElementById('serviceSearch').focus();
            }
            
            // Press Escape to clear search
            if (e.key === 'Escape') {
                const searchInput = document.getElementById('serviceSearch');
                if (document.activeElement === searchInput) {
                    searchInput.value = '';
                    filterServices('');
                    searchInput.blur();
                }
            }
        });

        // Add input event listeners for real-time quantity updates
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('quantity-input')) {
                const quantity = parseInt(e.target.value) || 0;
                
                // Ensure minimum quantity of 1
                if (quantity < 1) {
                    e.target.value = 1;
                }
                
                // Update summary in real-time
                updateSummary();
            }
        });

        // Smooth scrolling to service sections
        function scrollToServices() {
            document.getElementById('servicesContainer').scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }

        // Add service counter to category headers
        function updateCategoryCounters() {
            document.querySelectorAll('.category-header').forEach(function(header) {
                let serviceCount = 0;
                let currentElement = header.nextElementSibling;
                
                while (currentElement && !currentElement.classList.contains('category-header')) {
                    if (currentElement.classList.contains('service-item') && 
                        currentElement.style.display !== 'none') {
                        serviceCount++;
                    }
                    currentElement = currentElement.nextElementSibling;
                }
                
                // Update header text with count
                const originalText = header.textContent.replace(/\s*\(\d+\)$/, '');
                header.innerHTML = `<i class="ph-tag"></i>${originalText} <span style="font-weight: 400; opacity: 0.8;">(${serviceCount})</span>`;
            });
        }

        // Update category counters on search
        const originalFilterServices = filterServices;
        filterServices = function(searchTerm) {
            originalFilterServices(searchTerm);
            updateCategoryCounters();
        };

        // Initialize category counters
        setTimeout(updateCategoryCounters, 100);
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>