<?php
require_once 'includes/User.php';
require_once 'includes/db_config.php';
require_once 'includes/pricing.php';
$success_message = '';
$error_message = '';
if (isset($_SESSION['cart_success'])) {
    $success_message = $_SESSION['cart_success'];
    unset($_SESSION['cart_success']);
}
if (isset($_SESSION['cart_error'])) {
    $error_message = $_SESSION['cart_error'];
    unset($_SESSION['cart_error']);
}
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: /allura/service.php');
    exit();
}
$service_id = (int)$_GET['id'];
$usr = User::getCurrentUser();
$logged_in = User::isLoggedIn();
$service = null;
$service_options = [];
$error_msg = '';
$customer_type = 'guest';
$available_offers = [];
if ($logged_in) {
    try {
        $db = getDBConnection();
       
        $stmt = $db->prepare("
            SELECT u.*,
                   COUNT(o.id) as order_count,
                   CASE
                       WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'subscribed'
                       WHEN COUNT(o.id) >= 5 THEN 'regular'
                       WHEN COUNT(o.id) > 0 THEN 'normal'
                       ELSE 'new'
                   END as customer_type
            FROM users u
            LEFT JOIN orders o ON u.id = o.user_id
            WHERE u.id = ?
            GROUP BY u.id
        ");
        $stmt->execute(array($usr['id']));
        $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $customer_type = isset($user_data['customer_type']) ? $user_data['customer_type'] : 'new';
       
        $stmt = $db->prepare("
            SELECT * FROM offers
            WHERE status = 'active'
            AND start_date <= CURDATE()
            AND end_date >= CURDATE()
            AND (target_customers = 'all' OR target_customers = ?)
            AND (usage_limit IS NULL OR used_count < usage_limit)
            ORDER BY discount_value DESC
        ");
        $stmt->execute(array($customer_type));
        $available_offers = $stmt->fetchAll(PDO::FETCH_ASSOC);
       
    } catch (PDOException $e) {
        error_log("Error getting customer data: " . $e->getMessage());
    }
}
try {
    $db = getDBConnection();
   
    $stmt = $db->prepare("SELECT * FROM services WHERE id = ?");
    $stmt->execute(array($service_id));
    $service = $stmt->fetch(PDO::FETCH_ASSOC);
   
    if (!$service) {
        header('Location: service.php');
        exit();
    }
   
    $options_stmt = $db->prepare("SELECT * FROM service_options WHERE service_id = ? ORDER BY option_type, price_modifier");
    $options_stmt->execute(array($service_id));
    $all_options = $options_stmt->fetchAll(PDO::FETCH_ASSOC);
   
    foreach ($all_options as $option) {
        $service_options[$option['option_type']][] = $option;
    }
   
} catch (PDOException $e) {
    $error_msg = 'Error fetching service details: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($service['name'] ?? 'Service Details'); ?> - Allura Dry Clean</title>
    <?php include 'includes/header.php'; ?>
    <style>
        .main-image-wrapper {
    position: relative;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    background-color: #fff;
}

.main-image img {
    width: 100%;
    height: auto;
    max-height: 400px;
    object-fit: cover;
    display: block;
    border-radius: 12px;
}

.offer-badge {
    position: absolute;
    top: 15px;
    right: 15px;
    background-color: var(--error-color);
    color: var(--white-bg);
    padding: 8px 16px;
    border-radius: 20px;
    font-weight: bold;
    font-size: 0.95rem;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    z-index: 2;
}

.animated-badge {
    animation: pulseBadge 1.5s infinite;
}

@keyframes pulseBadge {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

        /*
         * Since the original style.css was not provided, I will create a minimal, modern style
         * to support the new layout and ensure a clean, appealing look.
         * The new_form_style.css will handle the form-specific layout.
         */
        :root {
            --primary-color: #007bff;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --error-color: #dc3545;
            --light-bg: #f8f9fa;
            --white-bg: #ffffff;
            --text-color: #343a40;
            --border-color: #dee2e6;
            --shadow-light: 0 4px 12px rgba(0, 0, 0, 0.05);
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--text-color);
            background-color: var(--light-bg);
            margin: 0;
            padding: 0;
        }
        .service-details-container {
            max-width: 1200px;
            margin: 40px auto;
            padding: 20px;
        }
        /* Notifications */
        .notification {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            font-weight: 500;
            box-shadow: var(--shadow-light);
        }
        .notification.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .notification.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .notification-icon {
            font-size: 1.2rem;
            margin-right: 10px;
        }
        .notification-close {
            margin-left: auto;
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: inherit;
            opacity: 0.6;
        }
        .notification-close:hover {
            opacity: 1;
        }
        /* Header and Breadcrumb */
        .page-header {
            margin-bottom: 30px;
        }
        .breadcrumb {
            font-size: 0.9rem;
            color: var(--secondary-color);
            margin-bottom: 10px;
        }
        .breadcrumb a {
            color: var(--primary-color);
            text-decoration: none;
        }
        .breadcrumb a:hover {
            text-decoration: underline;
        }
        h1 {
            font-size: 2.5rem;
            color: var(--text-color);
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 10px;
        }
        /* Main Content Layout */
        .service-details-content {
            display: flex;
            gap: 30px;
        }
        .service-image-section {
            flex: 1;
            min-width: 350px;
        }
        .service-info-section {
            flex: 2;
            min-width: 600px;
        }
        /* Image Section */
        .main-image {
            position: relative;
            margin-bottom: 20px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: var(--shadow-light);
        }
        .main-image img {
            width: 100%;
            height: auto;
            display: block;
            object-fit: cover;
        }
        .offer-badge {
            position: absolute;
            top: 15px;
            right: 15px;
            background-color: var(--error-color);
            color: var(--white-bg);
            padding: 8px 15px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 0.9rem;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }
        /* Additional Info Tabs */
        .info-tabs {
            display: flex;
            border-bottom: 2px solid var(--border-color);
            margin-bottom: 15px;
        }
        .tab-btn {
            background: none;
            border: none;
            padding: 10px 15px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            color: var(--secondary-color);
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
        }
        .tab-btn:hover {
            color: var(--primary-color);
        }
        .tab-btn.active {
            color: var(--primary-color);
            border-bottom: 3px solid var(--primary-color);
        }
        .tab-panel {
            padding: 10px 0;
        }
        .tab-panel h4 {
            color: var(--primary-color);
            margin-top: 0;
            margin-bottom: 10px;
        }
        .tab-panel ul, .tab-panel ol {
            list-style: none;
            padding: 0;
        }
        .tab-panel li {
            margin-bottom: 8px;
            padding-left: 1.5rem;
            position: relative;
        }
        .tab-panel li::before {
            content: '•'; /* Default bullet */
            position: absolute;
            left: 0;
            color: var(--primary-color);
            font-weight: bold;
        }
        /* Service Description */
        .service-description {
            margin-bottom: 30px;
        }
        .service-description h2 {
            font-size: 1.8rem;
            color: var(--text-color);
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 5px;
            margin-bottom: 15px;
        }
        /* Pricing Section */
        .pricing-section {
            margin-bottom: 30px;
        }
        .base-price {
            padding: 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background-color: var(--white-bg);
            box-shadow: var(--shadow-light);
        }
        .base-price h3 {
            margin-top: 0;
            font-size: 1.2rem;
            color: var(--secondary-color);
        }
        .base-price .price {
            font-size: 2rem;
            font-weight: bold;
            color: var(--primary-color);
            display: block;
        }
        .base-price small {
            font-size: 0.8rem;
            color: var(--secondary-color);
            font-weight: normal;
        }
        /* Tiered Pricing (keeping inline styles for now as they were in the original) */
        /* The original tiered pricing had extensive inline styles, which I will respect. */
        /* Order Form (The new_form_style.css handles the .order-form-wrapper) */
        .option-group {
            margin-bottom: 20px;
        }
        .option-label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: var(--text-color);
        }
        .service-option, .text-area, .quantity-field {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 5px;
            font-size: 14px;
        }
        .quantity-controls {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 5px;
        }
        .qty-btn {
            width: 30px;
            height: 30px;
            border: 1px solid var(--border-color);
            background: var(--white-bg);
            border-radius: 50%;
            cursor: pointer;
        }
        .option-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: flex-start;
        }
        .option-btn {
            padding: 12px 20px;
            border: 2px solid var(--border-color);
            background: var(--white-bg);
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            min-width: 150px;
            text-align: center;
        }
        .option-btn:hover {
            border-color: var(--primary-color);
        }
        .option-btn.active {
            border-color: var(--primary-color);
            background: var(--primary-color);
            color: var(--white-bg);
        }
        .selected-item {
            padding: 12px;
            background: var(--light-bg);
            border: 1px solid var(--success-color);
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            color: var(--success-color);
        }
        .checkmark {
            font-size: 1.2em;
        }
        /* Responsive adjustments */
        @media (max-width: 992px) {
            .service-details-content {
                flex-direction: column;
            }
            .service-image-section, .service-info-section {
                min-width: unset;
                width: 100%;
            }
        }
        @media (max-width: 576px) {
            .service-details-container {
                margin: 20px auto;
                padding: 10px;
            }
            h1 {
                font-size: 2rem;
            }
            .option-buttons {
                flex-direction: column;
            }
            .option-btn {
                min-width: auto;
            }
        }

    </style>

    <!-- <link rel="stylesheet" href="css/style.css"> -->
    <link rel="stylesheet" href="css/newstyle.css"> <!-- New CSS file for the form -->
</head>
<body>
    <div class="service-details-container">
        <?php if ($success_message): ?>
            <div class="notification success">
                <span class="notification-icon">✅</span>
                <span class="notification-message"><?php echo htmlspecialchars($success_message); ?></span>
                <button class="notification-close" onclick="this.parentElement.style.display='none'">&times;</button>
            </div>
        <?php endif; ?>
       
        <?php if ($error_message): ?>
            <div class="notification error">
                <span class="notification-icon">❌</span>
                <span class="notification-message"><?php echo htmlspecialchars($error_message); ?></span>
                <button class="notification-close" onclick="this.parentElement.style.display='none'">&times;</button>
            </div>
        <?php endif; ?>
       
        <?php if ($error_msg): ?>
            <div class="error-message">
                <p><?php echo htmlspecialchars($error_msg); ?></p>
                <a href="/allura/service.php" class="btn">Back to Services</a>
            </div>
        <?php elseif ($service): ?>
           
            <div class="page-header">
                <nav class="breadcrumb">
                    <a href="/allura/home.php">Home</a> >
                    <a href="/allura/service.php">Services</a> >
                    <span><?php echo htmlspecialchars($service['name']); ?></span>
                </nav>
                <h1><?php echo htmlspecialchars($service['name']); ?></h1>
            </div>
            <div class="service-details-content">
               <div class="service-image-section">
                   <div class="main-image-wrapper">
                       <div class="main-image">
                           <img id="main-service-image"
                                src="<?php echo htmlspecialchars($service['image']); ?>"
                                alt="<?php echo htmlspecialchars($service['name']); ?>"
                                onerror="this.src='img/default-service.png'">
                       </div>

                       <?php if ($logged_in && !empty($available_offers)): ?>
                       <div class="offer-badge animated-badge">
                           <?php
                               $applicable_offers = array_filter($available_offers, function($offer) use ($service) {
                                   return empty($offer['applicable_services']) || in_array($service['id'], json_decode($offer['applicable_services'], true));
                               });
                               if (!empty($applicable_offers)):
                                   $offer = reset($applicable_offers);
                           ?>
                               <?php if ($offer['discount_type'] === 'percentage'): ?>
                                   <?php echo $offer['discount_value']; ?>% OFF
                               <?php else: ?>
                                   SAR <?php echo number_format($offer['discount_value'], 2); ?> OFF
                               <?php endif; ?>
                           <?php endif; ?>
                       </div>
                       <?php endif; ?>
                   </div>
               </div>

                <div class="service-info-section">
                    <div class="service-description">
                        <h2>Service Description</h2>
                        <p><?php echo nl2br(htmlspecialchars($service['description'])); ?></p>
                    </div>
                  
                    <!-- NEW MULTI-STEP ORDER FORM -->
                    <div class="order-form-wrapper">
                        <div class="form-steps-indicator">
                            <div class="step active" data-step="1">1. Options</div>
                            <div class="step" data-step="2">2. Quantity</div>
                            <div class="step" data-step="3">3. Pickup/Delivery</div>
                        </div>
                        <form id="order-form" class="multi-step-form">
                            <!-- STEP 1: Service Options -->
                            <div class="form-step active" data-step="1">
                                <h3>Step 1: Choose Service Options</h3>
                               
                                <?php if ($service['category'] === 'household'): ?>
                                <div class="household-options-step">
                                    <?php if (isset($service_options['item_type'])): ?>
                                    <div class="option-group item-type-selector">
                                        <label class="option-label">Select Item Type:</label>
                                        <div class="item-type-buttons">
                                            <?php
                                            $images = ['pillows' => 'Pillows.png', 'blankets' => 'Blanket.png', 'curtains' => 'curtain.png', 'carpets' => 'carpet.png'];
                                            foreach ($service_options['item_type'] as $item):
                                            ?>
                                            <button type="button" class="item-type-btn"
                                                    style="background-image: url('img/<?php echo $images[$item['option_value']] ?? 'default-service.png'; ?>');"
                                                    data-item-type="<?php echo $item['option_value']; ?>"
                                                    data-option-id="<?php echo $item['id']; ?>"
                                                    onclick="selectHouseholdItem('<?php echo $item['option_value']; ?>', <?php echo $item['id']; ?>)">
                                                <span class="item-name"><?php echo htmlspecialchars($item['option_name']); ?></span>
                                            </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                   
                                    <div id="dynamic-household-options" style="display:none;">
                                        <!-- Dynamic options will be injected here -->
                                    </div>
                                </div>
                               
                                <?php elseif ($service['category'] === 'complete_washing'): ?>
                                <!-- Special layout for Regular & Specialized Cleaning -->
                                <div class="service-options-step">
                                    <?php
                                    // Service Type as buttons, including Dry Clean
                                    if (isset($service_options['service_type'])): ?>
                                    <div class="option-group" data-option-type="service_type">
                                        <label class="option-label">Service Type:</label>
                                        <div class="option-buttons">
                                            <?php foreach ($service_options['service_type'] as $option): ?>
                                            <button type="button" class="option-btn" data-option-id="<?php echo $option['id']; ?>" data-price="<?php echo $option['price_modifier']; ?>" data-value="<?php echo htmlspecialchars($option['option_value']); ?>">
                                                <?php echo htmlspecialchars($option['option_name']); ?>
                                                <?php if ($option['price_modifier'] != 0): ?>
                                                    (<?php echo ($option['price_modifier'] > 0 ? '+' : ''); ?>SAR <?php echo number_format($option['price_modifier'], 2); ?>)
                                                <?php endif; ?>
                                            </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php
                                    // Ironing Option as buttons
                                    if (isset($service_options['optional_ironing'])): ?>
                                    <div class="option-group" data-option-type="optional_ironing">
                                        <label class="option-label">Ironing Option:</label>
                                        <div class="option-buttons">
                                            <?php foreach ($service_options['optional_ironing'] as $option): ?>
                                            <button type="button" class="option-btn" data-option-id="<?php echo $option['id']; ?>" data-price="<?php echo $option['price_modifier']; ?>" data-value="<?php echo htmlspecialchars($option['option_value']); ?>">
                                                <?php echo htmlspecialchars($option['option_name']); ?>
                                                <?php if ($option['price_modifier'] != 0): ?>
                                                    (<?php echo ($option['price_modifier'] > 0 ? '+' : ''); ?>SAR <?php echo number_format($option['price_modifier'], 2); ?>)
                                                <?php endif; ?>
                                            </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($service_options['item_type'])): ?>
                                    <div class="option-group item-type-dropdown">
                                        <label class="option-label" for="itemTypeSelect">Select Item Type:</label>
                                        <select id="itemTypeSelect" name="item_type" class="service-option">
                                            <?php foreach ($service_options['item_type'] as $item): ?>
                                                <option value="<?php echo $item['option_value']; ?>" data-option-id="<?php echo $item['id']; ?>">
                                                    <?php echo htmlspecialchars($item['option_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <?php endif; ?>


                                    
                                    <?php
                                    // Item Type fixed as Clothes
                                    if (isset($service_options['item_type']) && count($service_options['item_type']) === 1): 
                                        $item_option = $service_options['item_type'][0];
                                    ?>
                                    <div class="option-group" data-option-type="item_type">
                                        <label class="option-label">Item Type:</label>
                                        <div class="selected-item">
                                            <?php echo htmlspecialchars($item_option['option_name']); ?> <span class="checkmark">✓</span>
                                        </div>
                                        <input type="hidden" name="item_type" value="<?php echo $item_option['id']; ?>" data-price="<?php echo $item_option['price_modifier']; ?>">
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php
                                    // Delivery Time as buttons
                                    if (isset($service_options['delivery_speed'])): ?>
                                    <div class="option-group" data-option-type="delivery_speed">
                                        <label class="option-label">Delivery Time:</label>
                                        <div class="option-buttons">
                                            <?php foreach ($service_options['delivery_speed'] as $option): ?>
                                            <button type="button" class="option-btn" data-option-id="<?php echo $option['id']; ?>" data-price="<?php echo $option['price_modifier']; ?>" data-value="<?php echo htmlspecialchars($option['option_value']); ?>">
                                                <?php echo htmlspecialchars($option['option_name']); ?>
                                                <?php if ($option['price_modifier'] != 0): ?>
                                                    (<?php echo ($option['price_modifier'] > 0 ? '+' : ''); ?>SAR <?php echo number_format($option['price_modifier'], 2); ?>)
                                                <?php endif; ?>
                                            </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php
                                    // Any other options
                                    foreach ($service_options as $option_type => $options):
                                        if (!in_array($option_type, ['service_type', 'optional_ironing', 'item_type', 'delivery_speed', 'gender'])):
                                    ?>
                                    <div class="option-group" <?php echo ($option_type === 'gender') ? 'style="display:none;"' : ''; ?>>
                                        <label class="option-label">
                                            <?php
                                            $option_labels = [
                                                'detergent' => 'Detergent Type:',
                                                'delivery_time' => 'Delivery Time:',
                                                'ironing_type' => 'Ironing Type:',
                                                'carpet_size' => 'Carpet Size:',
                                                'carpet_material' => 'Material Type:',
                                                'cleaning_material' => 'Cleaning Material:',
                                                'specialized_type' => 'Service Type:',
                                                'subscription_type' => 'Package Type:',
                                                'pickup_time' => 'Pickup Time:',
                                                'fabric_type' => 'Fabric Type:',
                                                'drying_level' => 'Drying Level:',
                                                'service_type' => 'Service Type:',
                                                'cleaning_method' => 'Cleaning Method:',
                                                'temperature' => 'Water Temperature:',
                                                'optional_ironing' => 'Ironing Option:',
                                                'garment_size' => 'Item Size (Length):',
                                                'gender' => 'Gender:',
                                                'shoe_type' => 'Shoe Type:'
                                            ];
                                            echo $option_labels[$option_type] ?? ucfirst(str_replace('_', ' ', $option_type)) . ':';
                                            ?>
                                        </label>
                                        <select class="service-option" data-option-type="<?php echo $option_type; ?>" <?php echo ($option_type !== 'gender') ? 'required' : ''; ?>>
                                            <option value="">Choose...</option>
                                            <?php foreach ($options as $option):
                                                $total_price = $service['price'] + $option['price_modifier'];
                                            ?>
                                            <option value="<?php echo $option['id']; ?>" data-price="<?php echo $option['price_modifier']; ?>" data-value="<?php echo htmlspecialchars($option['option_value']); ?>">
                                                <?php echo htmlspecialchars($option['option_name']); ?>
                                               <?php if ($option['price_modifier'] != 0): ?>
                                                   (<?php echo ($option['price_modifier'] > 0 ? '+' : ''); ?>SAR <?php echo number_format($option['price_modifier'], 2); ?>)
                                               <?php endif; ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <?php 
                                        endif;
                                    endforeach; 
                                    ?>
                                </div>
                                <?php else: ?>
                                <div class="service-options-step">
                                    <?php foreach ($service_options as $option_type => $options): ?>
                                    <div class="option-group" <?php echo ($option_type === 'gender') ? 'style="display:none;"' : ''; ?>>
                                        <label class="option-label">
                                            <?php
                                            $option_labels = [
                                                // 'detergent' => 'Detergent Type:',
                                                'delivery_time' => 'Delivery Time:',
                                                'ironing_type' => 'Ironing Type:',
                                                'carpet_size' => 'Carpet Size:',
                                                'carpet_material' => 'Material Type:',
                                                'cleaning_material' => 'Cleaning Material:',
                                                'specialized_type' => 'Service Type:',
                                                'subscription_type' => 'Package Type:',
                                                'pickup_time' => 'Pickup Time:',
                                                'fabric_type' => 'Fabric Type:',
                                                'item_type' => 'Item Type:',
                                                'drying_level' => 'Drying Level:',
                                                'service_type' => 'Service Type:',
                                                'cleaning_method' => 'Cleaning Method:',
                                                'temperature' => 'Water Temperature:',
                                                'optional_ironing' => 'Ironing Option:',
                                                'garment_size' => 'Item Size (Length):',
                                                'gender' => 'Gender:',
                                                'shoe_type' => 'Shoe Type:'
                                            ];
                                            echo $option_labels[$option_type] ?? ucfirst(str_replace('_', ' ', $option_type)) . ':';
                                            ?>
                                        </label>
                                        <select class="service-option" data-option-type="<?php echo $option_type; ?>" <?php echo ($option_type !== 'gender') ? 'required' : ''; ?>>
                                            <option value="">Choose...</option>
                                            <?php foreach ($options as $option):
                                                $total_price = $service['price'] + $option['price_modifier'];
                                            ?>
                                            <option value="<?php echo $option['id']; ?>" data-price="<?php echo $option['price_modifier']; ?>" data-value="<?php echo htmlspecialchars($option['option_value']); ?>">
                                                <?php echo htmlspecialchars($option['option_name']); ?>
                                               <?php if ($option['price_modifier'] != 0): ?>
                                                   (<?php echo ($option['price_modifier'] > 0 ? '+' : ''); ?>SAR <?php echo number_format($option['price_modifier'], 2); ?>)
                                               <?php endif; ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endif; ?>
                               
                                <div class="form-navigation">
                                    <button type="button" class="btn btn-secondary" onclick="window.location.href='/allura/service.php'">Back to Services</button>
                                    <button type="button" class="btn btn-primary next-step" data-next-step="2">Next: Quantity</button>
                                </div>
                            </div>
                            <!-- STEP 2: Quantity and Instructions -->
                            <div class="form-step" data-step="2">
                                <h3>Step 2: Specify Quantity and Instructions</h3>
                               
                                <?php if ($service['category'] === 'ironing' || $service['category'] === 'complete_washing' || $service['category'] === 'shoe_cleaning' || $service['category'] === 'household'): ?>
                                <div class="option-group quantity-section">
                                    <label for="quantity" class="option-label">
                                        <?php
                                        if ($service['category'] === 'complete_washing' || $service['category'] === 'ironing') {
                                            echo 'Number of pieces:';
                                        } elseif ($service['category'] === 'shoe_cleaning') {
                                            echo 'Number of shoe pairs:';
                                        } elseif ($service['category'] === 'household') {
                                            echo 'Number of <span id="item-label">Items</span>:';
                                        } else {
                                            echo 'Quantity:';
                                        }
                                        ?>
                                    </label>
                                    <div class="quantity-controls">
                                        <button type="button" class="qty-btn" onclick="changeQuantity(-1)">-</button>
                                        <input type="number" id="quantity" class="quantity-field" min="1" value="1" step="1" required>
                                        <button type="button" class="qty-btn" onclick="changeQuantity(1)">+</button>
                                    </div>
                                </div>
                                <?php endif; ?>
                               
                                <div class="option-group">
                                    <label for="special-instructions" class="option-label">Special Instructions (Optional):</label>
                                    <textarea id="special-instructions" class="text-area" rows="4" placeholder="Enter any special instructions or notes here..."></textarea>
                                </div>
                               
                                <div class="form-navigation">
                                    <button type="button" class="btn btn-secondary prev-step" data-prev-step="1">Previous: Options</button>
                                    <button type="button" class="btn btn-primary next-step" data-next-step="3">Next: Pickup/Delivery</button>
                                </div>
                            </div>
                            <!-- STEP 3: Pickup/Delivery and Final Review -->
                            <div class="form-step" data-step="3">
                                <h3>Step 3: Pickup and Delivery Details</h3>
                               
                                <div class="option-group">
                                  <label class="option-label">Service Preference:</label>
                                  <select id="pickup_option" name="pickup_option" class="service-option" required data-option-type="Pickup Option">
                                    <option value="">Select preference...</option>
                                    <option value="pickup">Pickup</option>
                                    <option value="delivery">Delivery</option>
                                  </select>
                                </div>
                                <div class="option-group" id="pickup-address-group" style="display:none;">
                                  <label class="option-label">Pickup Address:</label>
                                  <textarea id="pickup_address" name="pickup_address" class="text-area" rows="3" placeholder="Enter your pickup address..." data-option-type="pickup_address"></textarea>
                                </div>
                               
                                <?php if (isset($service_options['pickup_time'])): ?>
                                <div class="option-group" id="pickup-time-section">
                                    <label class="option-label">Pick-up Time Preference:</label>
                                    <select class="service-option" data-option-type="pickup_time">
                                        <option value="">Choose time slot...</option>
                                        <?php foreach ($service_options['pickup_time'] as $option):
                                            $total_price = $service['price'] + $option['price_modifier'];
                                        ?>
                                        <option value="<?php echo $option['id']; ?>" data-price="<?php echo $option['price_modifier']; ?>">
                                            <?php echo htmlspecialchars($option['option_name']); ?>
                                            <?php if ($option['price_modifier'] != 0): ?>
                                                (+SAR <?php echo number_format($option['price_modifier'], 2); ?>)
                                            <?php endif; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <?php endif; ?>
                               
                                <!-- Removed duplicate delivery_speed for complete_washing; handled in Step 1 -->
                                <?php if ($service['category'] !== 'complete_washing' && isset($service_options['delivery_speed'])): ?>
                                <div class="option-group" id="delivery-speed-section">
                                    <label class="option-label">Delivery Speed:</label>
                                    <select class="service-option" data-option-type="delivery_speed">
                                        <option value="">Choose delivery speed...</option>
                                        <?php foreach ($service_options['delivery_speed'] as $option): ?>
                                        <option value="<?php echo $option['id']; ?>" data-price="<?php echo $option['price_modifier']; ?>">
                                            <?php echo htmlspecialchars($option['option_name']); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <?php endif; ?>
                               
                                <div class="total-price-section">
                                    <h4>Order Summary</h4>
                                    <div class="price-breakdown">
                                        <div class="price-line">
                                            <span>Base Price:</span>
                                            <span id="base-total">SAR <?php echo number_format($service['price'], 2); ?></span>
                                        </div>
                                        <div class="price-line options-total" style="display: none;">
                                            <span>Additional Options:</span>
                                            <span id="options-total">SAR 0.00</span>
                                        </div>
                                        <div class="price-line total-line">
                                            <span><strong>Total Amount:</strong></span>
                                            <span id="final-total"><strong>SAR <?php echo number_format($service['price'], 2); ?></strong></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-navigation final-actions">
                                    <button type="button" class="btn btn-secondary prev-step" data-prev-step="2">Previous: Quantity</button>
                                    <?php if ($logged_in): ?>
                                        <button type="submit" class="btn btn-primary add-to-cart-btn">
                                            <?php echo $service['category'] === 'subscription' ? 'Subscribe Now' : 'Add to Cart'; ?>
                                        </button>
                                    <?php else: ?>
                                        <a href="/allura/login.php" class="btn btn-primary">Login to Order</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </form>
                    </div>
                    <!-- END NEW MULTI-STEP ORDER FORM -->
                </div>

            </div>
        <?php endif; ?>
    </div>
<!-- jQuery (add this if not already included) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <?php include 'includes/footer.php'; ?>
   
    <?php if ($logged_in): ?>
    <script>
        const serviceData = {
            id: <?php echo $service['id']; ?>,
            name: '<?php echo addslashes($service['name']); ?>',
            price: <?php echo $service['price']; ?>,
            category: '<?php echo $service['category']; ?>'
        };
       
        <?php if ($service['category'] === 'household'): ?>
        const householdOptionsData = <?php echo json_encode($service_options); ?>;
        <?php endif; ?>
       
        <?php if ($service['category'] === 'shoe_cleaning'): ?>
        const shoeImages = {
            'heels': 'img/Heels.png',
            'sports': 'img/Sports.png',
            'formal': 'img/Formal.png',
            'casual': 'img/Casual.png'
        };
       
        const defaultServiceImage = '<?php echo htmlspecialchars($service['image']); ?>';
       
        function updateMainServiceImage() {
            const shoeTypeSelect = document.querySelector('select[data-option-type="shoe_type"]');
            const mainImage = document.getElementById('main-service-image');
           
            if (shoeTypeSelect && shoeTypeSelect.value && mainImage) {
                const selectedOption = shoeTypeSelect.options[shoeTypeSelect.selectedIndex];
                const shoeType = selectedOption.getAttribute('data-value');
               
                if (shoeImages[shoeType]) {
                    mainImage.src = shoeImages[shoeType];
                } else {
                    mainImage.src = defaultServiceImage;
                }
            } else if (mainImage) {
                mainImage.src = defaultServiceImage;
            }
        }
       
        document.addEventListener('DOMContentLoaded', function() {
            const shoeTypeSelect = document.querySelector('select[data-option-type="shoe_type"]');
            if (shoeTypeSelect) {
                shoeTypeSelect.addEventListener('change', updateMainServiceImage);
            }
        });
        <?php endif; ?>
        
        // Tab functionality (if needed)
        function showTab(tabName) {
            const tabs = document.querySelectorAll('.tab-panel');
            const btns = document.querySelectorAll('.tab-btn');
            tabs.forEach(tab => tab.classList.remove('active'));
            btns.forEach(btn => btn.classList.remove('active'));
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');
        }
        
        // Quantity changer
        function changeQuantity(delta) {
            const qtyInput = document.getElementById('quantity');
            let qty = parseInt(qtyInput.value) || 1;
            qty = Math.max(1, qty + delta);
            qtyInput.value = qty;
            updateTotal();
        }
        
        // Real-time total update
        function updateTotal() {
            const basePrice = serviceData.price;
            const quantity = parseInt(document.getElementById('quantity')?.value) || 1;
            let baseTotal = basePrice * quantity;
            let optionsTotal = 0;
            
            // From selects
            document.querySelectorAll('.service-option').forEach(select => {
                if (select.value) {
                    const priceMod = parseFloat(select.selectedOptions[0]?.getAttribute('data-price')) || 0;
                    optionsTotal += priceMod * quantity;
                }
            });
            
            // From button hiddens
            document.querySelectorAll('input[type="hidden"][data-price]').forEach(hidden => {
                const priceMod = parseFloat(hidden.getAttribute('data-price')) || 0;
                optionsTotal += priceMod * quantity;
            });
            
            const finalTotal = baseTotal + optionsTotal;
            document.getElementById('base-total').textContent = 'SAR ' + baseTotal.toFixed(2);
            const optionsEl = document.querySelector('.options-total');
            if (optionsTotal > 0) {
                optionsEl.style.display = 'flex';
                document.getElementById('options-total').textContent = 'SAR ' + optionsTotal.toFixed(2);
            } else {
                optionsEl.style.display = 'none';
            }
            document.getElementById('final-total').innerHTML = '<strong>SAR ' + finalTotal.toFixed(2) + '</strong>';
        }
        
        // Button selection for option groups
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.option-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const buttons = this.parentElement.querySelectorAll('.option-btn');
                    buttons.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    
                    const group = this.closest('.option-group');
                    let hidden = group.querySelector('input[type="hidden"]');
                    if (!hidden) {
                        hidden = document.createElement('input');
                        hidden.type = 'hidden';
                        hidden.name = group.getAttribute('data-option-type');
                        group.appendChild(hidden);
                    }
                    hidden.value = this.getAttribute('data-option-id');
                    hidden.setAttribute('data-price', this.getAttribute('data-price'));
                    
                    updateTotal();
                });
            });
            
            // Set defaults for complete_washing
            if (serviceData.category === 'complete_washing') {
                // Service Type: first button (assuming order: Regular Wash & Dry, Specialized Cleaning, Dry Clean)
                const serviceBtns = document.querySelectorAll('[data-option-type="service_type"] .option-btn');
                if (serviceBtns.length > 0) serviceBtns[0].click();
                
                // Ironing Option: second button
                const ironingBtns = document.querySelectorAll('[data-option-type="optional_ironing"] .option-btn');
                if (ironingBtns.length > 1) ironingBtns[1].click();
                
                // Delivery Speed: first button
                const deliveryBtns = document.querySelectorAll('[data-option-type="delivery_speed"] .option-btn');
                if (deliveryBtns.length > 0) deliveryBtns[0].click();
            }
            
            // Initial update
            updateTotal();
            
            // Listen for changes
            document.addEventListener('change', updateTotal);
            document.addEventListener('input', updateTotal);
        });
        
        // Pickup option handler
        $(document).ready(function() {
            $('#pickup_option').on('change', function() {
                if ($(this).val() === 'pickup') {
                    $('#pickup-address-group').slideDown(300);
                    $('#pickup_address').attr('required', true);
                } else {
                    $('#pickup-address-group').slideUp(300);
                    $('#pickup_address').removeAttr('required').val('');
                }
                updateTotal();
            });
        });
    </script>
    <script src="js/service_details_new.js"></script>
    <?php endif; ?>
</body>
</html>