<?php
session_start();
require_once __DIR__ . '/config/db.php';

$service_id = isset($_GET['service_id']) ? intval($_GET['service_id']) : 0;
$service_name = isset($_GET['service']) ? htmlspecialchars(urldecode($_GET['service'])) : '';
$isLoggedIn = isset($_SESSION['user_id']);
$userName = isset($_SESSION['user_name']) ? htmlspecialchars($_SESSION['user_name']) : '';
$userEmail = isset($_SESSION['user_email']) ? htmlspecialchars($_SESSION['user_email']) : '';
$userPhone = isset($_SESSION['user_phone']) ? htmlspecialchars($_SESSION['user_phone']) : '';

// Create service_bookings table
$connection->query("CREATE TABLE IF NOT EXISTS service_bookings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT DEFAULT NULL,
    service_id INT NOT NULL,
    service_name VARCHAR(255) NOT NULL,
    customer_name VARCHAR(255) NOT NULL,
    customer_email VARCHAR(255) NOT NULL,
    customer_phone VARCHAR(50) NOT NULL,
    address TEXT NOT NULL,
    city VARCHAR(100) DEFAULT '',
    pincode VARCHAR(20) DEFAULT '',
    area_sqft INT DEFAULT 0,
    preferred_date DATE DEFAULT NULL,
    preferred_time VARCHAR(50) DEFAULT '',
    budget_range VARCHAR(100) DEFAULT '',
    selected_products LONGTEXT DEFAULT NULL,
    estimated_total DECIMAL(12,2) DEFAULT 0,
    notes TEXT DEFAULT NULL,
    status VARCHAR(50) DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_user_id (user_id),
    INDEX idx_service_id (service_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$selectedProductsColumn = $connection->query("SHOW COLUMNS FROM service_bookings LIKE 'selected_products'");
if ($selectedProductsColumn && $selectedProductsColumn->num_rows === 0) {
    $connection->query("ALTER TABLE service_bookings ADD COLUMN selected_products LONGTEXT DEFAULT NULL AFTER budget_range");
}

$estimatedTotalColumn = $connection->query("SHOW COLUMNS FROM service_bookings LIKE 'estimated_total'");
if ($estimatedTotalColumn && $estimatedTotalColumn->num_rows === 0) {
    $connection->query("ALTER TABLE service_bookings ADD COLUMN estimated_total DECIMAL(12,2) DEFAULT 0 AFTER selected_products");
}

// Fetch service info
$service = null;
if ($service_id > 0) {
    $stmt = $connection->prepare("SELECT id, title, image, description, price, area_sqft, duration FROM services WHERE id = ? AND is_active = 1");
    if ($stmt) {
        $stmt->bind_param('i', $service_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result && $result->num_rows > 0) {
            $service = $result->fetch_assoc();
            if (!$service_name) $service_name = htmlspecialchars($service['title']);
        }
        $stmt->close();
    }
}

// Fetch products for this service
$products = [];
if ($service_id > 0) {
    $pStmt = $connection->prepare("SELECT product_name, cost, quantity FROM service_products WHERE service_id = ? ORDER BY sort_order ASC");
    if ($pStmt) {
        $pStmt->bind_param('i', $service_id);
        $pStmt->execute();
        $pRes = $pStmt->get_result();
        while ($row = $pRes->fetch_assoc()) $products[] = $row;
        $pStmt->close();
    }
}

$serviceBasePrice = isset($service['price']) ? (float)$service['price'] : 0.0;
$selectedProductIndexes = [];
$selectedProductsForSummary = [];
$selectedProductsTotal = 0.0;
$estimatedGrandTotal = $serviceBasePrice;

// Handle form submission
$successMsg = '';
$errorMsg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cName = trim($_POST['customer_name'] ?? '');
    $cEmail = trim($_POST['customer_email'] ?? '');
    $cPhone = trim($_POST['customer_phone'] ?? '');
    $cAddress = trim($_POST['address'] ?? '');
    $cCity = trim($_POST['city'] ?? '');
    $cPincode = trim($_POST['pincode'] ?? '');
    $cArea = intval($_POST['area_sqft'] ?? 0);
    $cDate = trim($_POST['preferred_date'] ?? '');
    $cTime = trim($_POST['preferred_time'] ?? '');
    $cNotes = trim($_POST['notes'] ?? '');
    $cServiceId = intval($_POST['service_id'] ?? 0);
    $cServiceName = trim($_POST['service_name'] ?? '');
    $userId = $isLoggedIn ? intval($_SESSION['user_id']) : null;
    $selectedProductIndexes = array_values(array_unique(array_map('intval', $_POST['selected_products'] ?? [])));

    foreach ($selectedProductIndexes as $productIndex) {
        if (!isset($products[$productIndex])) {
            continue;
        }

        $product = $products[$productIndex];
        $qty = is_numeric($product['quantity']) ? (float)$product['quantity'] : 1.0;
        $unitCost = (float)($product['cost'] ?? 0);
        $lineCost = $unitCost * $qty;
        $selectedProductsTotal += $lineCost;
        $selectedProductsForSummary[] = [
            'name' => (string)($product['product_name'] ?? ''),
            'quantity' => $qty,
            'unit_cost' => $unitCost,
            'line_cost' => $lineCost
        ];
    }

    $estimatedGrandTotal = $serviceBasePrice + $selectedProductsTotal;

    if (!$cName || !$cEmail || !$cPhone || !$cAddress) {
        $errorMsg = 'Please fill in all required fields.';
    } elseif (!filter_var($cEmail, FILTER_VALIDATE_EMAIL)) {
        $errorMsg = 'Please enter a valid email address.';
    } else {
        $selectedProductsJson = !empty($selectedProductsForSummary) ? json_encode($selectedProductsForSummary, JSON_UNESCAPED_UNICODE) : null;
        $cBudget = '';
        $ins = $connection->prepare("INSERT INTO service_bookings (user_id, service_id, service_name, customer_name, customer_email, customer_phone, address, city, pincode, area_sqft, preferred_date, preferred_time, budget_range, selected_products, estimated_total, notes, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')");
        if ($ins) {
            $ins->bind_param('iisssssssissssds', $userId, $cServiceId, $cServiceName, $cName, $cEmail, $cPhone, $cAddress, $cCity, $cPincode, $cArea, $cDate, $cTime, $cBudget, $selectedProductsJson, $estimatedGrandTotal, $cNotes);
            if ($ins->execute()) {
                $successMsg = 'Your service booking has been submitted successfully! Our team will contact you shortly.';
                $selectedProductIndexes = [];
                $selectedProductsForSummary = [];
                $selectedProductsTotal = 0.0;
                $estimatedGrandTotal = $serviceBasePrice;
            } else {
                $errorMsg = 'An error occurred. Please try again.';
            }
            $ins->close();
        }
    }
}

$page_title = 'Book Service' . ($service_name ? ' - ' . $service_name : '') . ' | Faren Architects';
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <meta name="description" content="Book your interior design service with Faren Architects. Fill the form and our team will get in touch.">
    <link rel="icon" type="image/png" sizes="32x32" href="assets/img/favicons/favicon-32x32.png">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        :root {
            --bk-bg: #f4efe8;
            --bk-surface: #ffffff;
            --bk-ink: #1f1b17;
            --bk-muted: #6f665d;
            --bk-accent: #b58a5a;
            --bk-accent-dark: #8a643f;
            --bk-border: #e7dbce;
            --bk-success: #1b8a67;
            --bk-error: #c84d4d;
        }
        * { box-sizing: border-box; }
        body { font-family: 'Inter', 'Segoe UI', sans-serif; }

        .booking-page {
            min-height: 100vh;
            background:
                radial-gradient(circle at 8% 12%, rgba(181,138,90,0.15), transparent 34%),
                radial-gradient(circle at 92% 80%, rgba(131,98,66,0.10), transparent 36%),
                linear-gradient(180deg, #f8f4ee 0%, #f2ece4 100%);
            padding: 0;
        }

        .booking-shell {
            max-width: 100%;
            margin: 0 auto;
            padding: 24px 16px 60px;
        }

        /* Back link */
        .bk-back {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: var(--bk-accent-dark);
            text-decoration: none;
            font-weight: 700;
            font-size: 14px;
            margin-bottom: 24px;
            transition: gap 0.2s;
        }
        .bk-back:hover { gap: 12px; color: var(--bk-accent-dark); }

        /* Layout */
        .booking-grid {
            display: grid;
            grid-template-columns: 1fr 380px;
            gap: 28px;
            align-items: start;
        }

        /* Card base */
        .bk-card {
            background: var(--bk-surface);
            border: 1px solid var(--bk-border);
            border-radius: 20px;
            box-shadow: 0 12px 36px rgba(42,28,13,0.07);
            overflow: hidden;
        }

        /* Form card */
        .bk-form-card { padding: 32px; }
        .bk-form-title {
            font-size: clamp(22px, 4vw, 30px);
            font-weight: 800;
            color: var(--bk-ink);
            margin: 0 0 6px;
        }
        .bk-form-sub {
            color: var(--bk-muted);
            font-size: 14px;
            margin: 0 0 28px;
        }

        /* Form sections */
        .bk-section-label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            font-weight: 800;
            color: var(--bk-accent-dark);
            text-transform: uppercase;
            letter-spacing: 0.1em;
            margin-bottom: 16px;
            margin-top: 28px;
        }
        .bk-section-label:first-of-type { margin-top: 0; }
        .bk-section-label i { font-size: 14px; }

        /* Field grid */
        .bk-field-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }
        .bk-field-full { grid-column: 1 / -1; }
        .bk-preference-grid > div:nth-child(2) { display: none; }

        /* Labels & inputs */
        .bk-label {
            display: block;
            font-size: 12px;
            font-weight: 700;
            color: var(--bk-muted);
            text-transform: uppercase;
            letter-spacing: 0.06em;
            margin-bottom: 6px;
        }
        .bk-label .required { color: var(--bk-error); }

        .bk-input, .bk-select, .bk-textarea {
            width: 100%;
            padding: 12px 16px;
            border: 1.5px solid var(--bk-border);
            border-radius: 12px;
            font-size: 14px;
            font-family: inherit;
            color: var(--bk-ink);
            background: #fdfbf8;
            transition: border-color 0.2s, box-shadow 0.2s;
            outline: none;
        }
        .bk-input:focus, .bk-select:focus, .bk-textarea:focus {
            border-color: var(--bk-accent);
            box-shadow: 0 0 0 3px rgba(181,138,90,0.12);
        }
        .bk-textarea { resize: vertical; min-height: 100px; }
        .bk-select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%236f665d' stroke-width='1.5' fill='none'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 14px center; padding-right: 36px; }

        /* Submit */
        .bk-submit-btn {
            width: 100%;
            padding: 16px;
            border: none;
            border-radius: 14px;
            font-size: 16px;
            font-weight: 800;
            color: #fff;
            background: linear-gradient(135deg, var(--bk-accent), var(--bk-accent-dark));
            box-shadow: 0 10px 26px rgba(138,100,63,0.30);
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            margin-top: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        .bk-submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 14px 32px rgba(138,100,63,0.38);
        }

        /* Messages */
        .bk-msg {
            padding: 14px 18px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .bk-msg.success {
            background: #edf9f4;
            border: 1px solid #c5e8d8;
            color: #1b6b50;
        }
        .bk-msg.error {
            background: #fdf0f0;
            border: 1px solid #ecc;
            color: #993333;
        }

        /* ---- Sidebar ---- */
        .bk-sidebar { position: static; top: 100px; }

        .bk-service-preview {
            padding: 0;
        }
        .bk-preview-img {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }
        .bk-preview-body { padding: 20px; }
        .bk-preview-title {
            font-size: 20px;
            font-weight: 800;
            color: var(--bk-ink);
            margin: 0 0 8px;
        }
        .bk-preview-desc {
            font-size: 13px;
            color: var(--bk-muted);
            line-height: 1.6;
            margin: 0 0 16px;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .bk-preview-meta {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 16px;
        }
        .bk-meta-item {
            background: #faf6f0;
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 10px 12px;
            text-align: center;
        }
        .bk-meta-label {
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: var(--bk-muted);
            margin-bottom: 2px;
        }
        .bk-meta-value {
            font-size: 16px;
            font-weight: 800;
            color: var(--bk-accent-dark);
        }

        /* Products in sidebar */
        .bk-products-title {
            font-size: 12px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            color: var(--bk-accent-dark);
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .bk-product-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f2ece4;
            font-size: 13px;
        }
        .bk-product-row:last-child { border-bottom: none; }
        .bk-product-name { color: var(--bk-ink); font-weight: 600; }
        .bk-product-cost { color: var(--bk-accent-dark); font-weight: 800; }

        .bk-total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 14px 0 0;
            margin-top: 10px;
            border-top: 2px solid var(--bk-border);
            font-size: 15px;
            font-weight: 800;
        }
        .bk-total-label { color: var(--bk-ink); }
        .bk-total-value { color: var(--bk-accent-dark); font-size: 20px; }

        .bk-product-picker {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 14px;
        }

        .bk-product-option {
            position: relative;
        }

        .bk-product-option input {
            position: absolute;
            opacity: 0;
            pointer-events: none;
        }

        .bk-product-card {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 14px;
            padding: 16px;
            border: 1.5px solid var(--bk-border);
            border-radius: 16px;
            background: #fdfbf8;
            cursor: pointer;
            transition: border-color 0.2s, box-shadow 0.2s, transform 0.2s, background 0.2s;
            min-height: 100%;
        }

        .bk-product-option input:checked + .bk-product-card {
            border-color: var(--bk-accent);
            background: #fff8f0;
            box-shadow: 0 12px 26px rgba(181,138,90,0.14);
            transform: translateY(-2px);
        }

        .bk-product-copy {
            display: flex;
            flex-direction: column;
            gap: 6px;
            min-width: 0;
        }

        .bk-product-copy strong,
        .bk-product-copy span,
        .bk-product-copy small {
            overflow-wrap: anywhere;
        }

        .bk-product-badge {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            border: 1.5px solid var(--bk-border);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: transparent;
            background: #fff;
            flex: 0 0 auto;
            transition: all 0.2s;
        }

        .bk-product-option input:checked + .bk-product-card .bk-product-badge {
            border-color: var(--bk-accent);
            background: var(--bk-accent);
            color: #fff;
        }

        .bk-summary-note {
            margin-top: 12px;
            font-size: 12px;
            color: var(--bk-muted);
            line-height: 1.6;
        }

        /* Responsive */
        @media (max-width: 900px) {
            .booking-grid {
                grid-template-columns: 1fr;
            }
            .bk-sidebar {
                position: static;
                order: -1;
            }
            .bk-preview-img { height: 180px; }
            .bk-product-picker {
                grid-template-columns: 1fr;
            }
        }
        @media (max-width: 600px) {
            .booking-shell { padding: 16px 12px 40px; }
            .bk-form-card { padding: 20px 16px; }
            .bk-field-grid { grid-template-columns: 1fr; }
            .bk-form-title { font-size: 20px; }
            .bk-preview-body { padding: 16px; }
            .bk-preview-img { height: 150px; }
            .bk-preview-meta { grid-template-columns: 1fr; }
            .bk-product-card {
                padding: 14px;
                border-radius: 14px;
            }
            .bk-total-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
            }
        }
        @media (max-width: 400px) {
            .bk-submit-btn { font-size: 14px; padding: 14px; }
        }
    </style>
</head>
<body>
    <?php include 'header-php.php'; ?>

    <main class="booking-page">
        <div class="booking-shell">
            <a href="<?php echo $service_id > 0 ? 'service-details.php?id=' . $service_id : 'service.php'; ?>" class="bk-back">
                <i class="fa-solid fa-arrow-left"></i> Back to <?php echo $service_id > 0 ? 'Service Details' : 'Services'; ?>
            </a>

            <div class="booking-grid">
                <!-- FORM -->
                <div class="bk-card bk-form-card">
                    <h1 class="bk-form-title">Book Your Service</h1>
                    <p class="bk-form-sub">Fill in the details below and our design team will reach out to schedule your service.</p>

                    <?php if ($successMsg): ?>
                        <div class="bk-msg success"><i class="fa-solid fa-circle-check"></i> <?php echo $successMsg; ?></div>
                    <?php endif; ?>
                    <?php if ($errorMsg): ?>
                        <div class="bk-msg error"><i class="fa-solid fa-circle-exclamation"></i> <?php echo $errorMsg; ?></div>
                    <?php endif; ?>

                    <form method="POST" action="" id="bookingForm">
                        <input type="hidden" name="service_id" value="<?php echo $service_id; ?>">
                        <input type="hidden" name="service_name" value="<?php echo $service_name; ?>">

                        <!-- Personal Info -->
                        <div class="bk-section-label"><i class="fa-solid fa-user"></i> Personal Information</div>
                        <div class="bk-field-grid">
                            <div>
                                <label class="bk-label">Full Name <span class="required">*</span></label>
                                <input class="bk-input" type="text" name="customer_name" required placeholder="John Doe" value="<?php echo $userName; ?>">
                            </div>
                            <div>
                                <label class="bk-label">Phone <span class="required">*</span></label>
                                <input class="bk-input" type="tel" name="customer_phone" required placeholder="+91 98765 43210" value="<?php echo $userPhone; ?>">
                            </div>
                            <div class="bk-field-full">
                                <label class="bk-label">Email <span class="required">*</span></label>
                                <input class="bk-input" type="email" name="customer_email" required placeholder="john@example.com" value="<?php echo $userEmail; ?>">
                            </div>
                        </div>

                        <!-- Location -->
                        <div class="bk-section-label"><i class="fa-solid fa-location-dot"></i> Location Details</div>
                        <div class="bk-field-grid">
                            <div class="bk-field-full">
                                <label class="bk-label">Address <span class="required">*</span></label>
                                <textarea class="bk-textarea" name="address" required placeholder="Full address including house/flat number, street, landmark..." rows="3"></textarea>
                            </div>
                            <div>
                                <label class="bk-label">City</label>
                                <input class="bk-input" type="text" name="city" placeholder="Mumbai">
                            </div>
                            <div>
                                <label class="bk-label">Pincode</label>
                                <input class="bk-input" type="text" name="pincode" placeholder="400001" maxlength="10">
                            </div>
                        </div>

                        <!-- Service Preferences -->
                        <div class="bk-section-label"><i class="fa-solid fa-sliders"></i> Service Preferences</div>
                        <div class="bk-field-grid bk-preference-grid">
                            <div>
                                <label class="bk-label">Area (sqft)</label>
                                <input class="bk-input" type="number" name="area_sqft" placeholder="1200" min="0" value="<?php echo isset($_POST['area_sqft']) ? htmlspecialchars((string)$_POST['area_sqft']) : ''; ?>">
                            </div>
                            <div>
                                <label class="bk-label">Budget Range</label>
                                <select class="bk-select" name="budget_range">
                                    <option value="">Select budget</option>
                                    <option value="Under ₹50,000">Under ₹50,000</option>
                                    <option value="₹50,000 - ₹1,00,000">₹50,000 - ₹1,00,000</option>
                                    <option value="₹1,00,000 - ₹3,00,000">₹1,00,000 - ₹3,00,000</option>
                                    <option value="₹3,00,000 - ₹5,00,000">₹3,00,000 - ₹5,00,000</option>
                                    <option value="₹5,00,000 - ₹10,00,000">₹5,00,000 - ₹10,00,000</option>
                                    <option value="Above ₹10,00,000">Above ₹10,00,000</option>
                                </select>
                            </div>
                            <div>
                                <label class="bk-label">Preferred Date</label>
                                <input class="bk-input" type="date" name="preferred_date" min="<?php echo date('Y-m-d'); ?>" value="<?php echo isset($_POST['preferred_date']) ? htmlspecialchars((string)$_POST['preferred_date']) : ''; ?>">
                            </div>
                            <div>
                                <label class="bk-label">Preferred Time</label>
                                <select class="bk-select" name="preferred_time">
                                    <option value="">Select time slot</option>
                                    <option value="Morning (9AM - 12PM)" <?php echo (($_POST['preferred_time'] ?? '') === 'Morning (9AM - 12PM)') ? 'selected' : ''; ?>>Morning (9AM - 12PM)</option>
                                    <option value="Afternoon (12PM - 3PM)" <?php echo (($_POST['preferred_time'] ?? '') === 'Afternoon (12PM - 3PM)') ? 'selected' : ''; ?>>Afternoon (12PM - 3PM)</option>
                                    <option value="Evening (3PM - 6PM)" <?php echo (($_POST['preferred_time'] ?? '') === 'Evening (3PM - 6PM)') ? 'selected' : ''; ?>>Evening (3PM - 6PM)</option>
                                    <option value="Flexible" <?php echo (($_POST['preferred_time'] ?? '') === 'Flexible') ? 'selected' : ''; ?>>Flexible</option>
                                </select>
                            </div>
                            <?php if (!empty($products)): ?>
                            <div class="bk-field-full">
                                <label class="bk-label">Select Products To Include</label>
                                <div class="bk-product-picker">
                                    <?php foreach ($products as $productIndex => $product): ?>
                                        <?php
                                            $productQty = is_numeric($product['quantity']) ? (float)$product['quantity'] : 1.0;
                                            $productLineCost = ((float)($product['cost'] ?? 0)) * $productQty;
                                            $isChecked = in_array($productIndex, $selectedProductIndexes, true);
                                        ?>
                                        <label class="bk-product-option">
                                            <input type="checkbox" name="selected_products[]" value="<?php echo (int)$productIndex; ?>" data-product-cost="<?php echo htmlspecialchars(number_format($productLineCost, 2, '.', '')); ?>" <?php echo $isChecked ? 'checked' : ''; ?>>
                                            <span class="bk-product-card">
                                                <span class="bk-product-copy">
                                                    <strong><?php echo htmlspecialchars($product['product_name'] ?? 'Product'); ?></strong>
                                                    <span><?php echo htmlspecialchars(rtrim(rtrim(number_format($productQty, 2, '.', ''), '0'), '.')); ?> item(s)</span>
                                                    <small>Unit price: Rs <?php echo number_format((float)($product['cost'] ?? 0), 0); ?></small>
                                                </span>
                                                <span style="display:flex;flex-direction:column;align-items:flex-end;gap:10px;">
                                                    <span class="bk-product-badge"><i class="fa-solid fa-check"></i></span>
                                                    <strong class="bk-product-cost">Rs <?php echo number_format($productLineCost, 0); ?></strong>
                                                </span>
                                            </span>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <p class="bk-summary-note">The estimate includes the base service price and any products you select above. Final pricing can be refined after site measurements and design review.</p>
                            <?php endif; ?>
                            <div class="bk-field-full">
                                <label class="bk-label">Additional Notes</label>
                                <textarea class="bk-textarea" name="notes" placeholder="Describe your vision, specific requirements, style preferences..."><?php echo isset($_POST['notes']) ? htmlspecialchars((string)$_POST['notes']) : ''; ?></textarea>
                            </div>
                        </div>

                        <button class="bk-submit-btn" type="submit">
                            <i class="fa-solid fa-paper-plane"></i> Submit Booking Request
                        </button>
                    </form>
                </div>

                <!-- SIDEBAR -->
                <div class="bk-sidebar">
                    <?php if ($service): ?>
                    <div class="bk-card bk-service-preview">
                        <img class="bk-preview-img" src="<?php echo htmlspecialchars($service['image'] ?? 'assets/img/service/service_2_1.jpg'); ?>" alt="<?php echo $service_name; ?>">
                        <div class="bk-preview-body">
                            <h3 class="bk-preview-title"><?php echo $service_name; ?></h3>
                            <p class="bk-preview-desc"><?php echo htmlspecialchars($service['description'] ?? ''); ?></p>

                            <div class="bk-preview-meta">
                                <?php if (!empty($service['price'])): ?>
                                <div class="bk-meta-item">
                                    <div class="bk-meta-label">Price</div>
                                    <div class="bk-meta-value">₹<?php echo number_format(floatval($service['price'])); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if (!empty($service['duration'])): ?>
                                <div class="bk-meta-item">
                                    <div class="bk-meta-label">Duration</div>
                                    <div class="bk-meta-value"><?php echo htmlspecialchars($service['duration']); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if (!empty($service['area_sqft'])): ?>
                                <div class="bk-meta-item">
                                    <div class="bk-meta-label">Area</div>
                                    <div class="bk-meta-value"><?php echo number_format(intval($service['area_sqft'])); ?> sqft</div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <?php if (!empty($products)): ?>
                            <div class="bk-products-title"><i class="fa-solid fa-boxes-stacked"></i> Selected Products</div>
                            <?php
                            $totalCost = 0;
                            foreach ($products as $pIndex => $p):
                                $qty = is_numeric($p['quantity']) ? floatval($p['quantity']) : 1;
                                $lineCost = floatval($p['cost']) * $qty;
                                $totalCost += $lineCost;
                            ?>
                                <div class="bk-product-row" data-product-summary-row data-product-index="<?php echo (int)$pIndex; ?>">
                                    <span class="bk-product-name"><?php echo htmlspecialchars($p['product_name']); ?> <small style="color:#999">×<?php echo $p['quantity']; ?></small></span>
                                    <span class="bk-product-cost">₹<?php echo number_format($lineCost); ?></span>
                                </div>
                            <?php endforeach; ?>
                            <div class="bk-product-row" id="bkBaseServicePriceRow">
                                <span class="bk-product-name">Base service price</span>
                                <span class="bk-product-cost" id="bkBaseServicePrice" data-base-price="<?php echo htmlspecialchars(number_format($serviceBasePrice, 2, '.', '')); ?>">Rs <?php echo number_format($serviceBasePrice); ?></span>
                            </div>
                            <div class="bk-total-row">
                                <span class="bk-total-label">Estimated Total</span>
                                <span class="bk-total-value">₹<?php echo number_format($estimatedGrandTotal); ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="bk-card" style="padding:32px; text-align:center; color:var(--bk-muted);">
                        <i class="fa-solid fa-paintbrush" style="font-size:40px; opacity:0.3; margin-bottom:12px; display:block;"></i>
                        <p style="font-size:14px; margin:0;">Select a service from our <a href="service.php" style="color:var(--bk-accent-dark); font-weight:700;">services page</a> to see details here.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </main>

    <?php include 'footer-section.html'; ?>

    <div class="scroll-top">
        <svg class="progress-circle svg-content" width="100%" height="100%" viewbox="-1 -1 102 102">
            <path d="M50,1 a49,49 0 0,1 0,98 a49,49 0 0,1 0,-98" style="transition: stroke-dashoffset 10ms linear 0s; stroke-dasharray: 307.919, 307.919; stroke-dashoffset: 307.919;"></path>
        </svg>
    </div>

    <script src="assets/js/vendor/jquery-3.7.1.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script>
        (function() {
            const bookingForm = document.getElementById('bookingForm');
            if (!bookingForm) return;

            const productCheckboxes = bookingForm.querySelectorAll('input[name="selected_products[]"]');
            const basePriceElement = document.getElementById('bkBaseServicePrice');
            const totalValueElement = document.querySelector('.bk-total-value');
            const summaryRows = document.querySelectorAll('[data-product-summary-row]');

            const formatCurrency = (value) => 'Rs ' + Number(value || 0).toLocaleString('en-IN', {
                maximumFractionDigits: 0
            });

            const updateEstimate = () => {
                const basePrice = basePriceElement ? parseFloat(basePriceElement.dataset.basePrice || '0') : 0;
                let selectedTotal = 0;
                let selectedCount = 0;

                productCheckboxes.forEach((checkbox) => {
                    const row = document.querySelector('[data-product-summary-row][data-product-index="' + checkbox.value + '"]');
                    const lineCost = parseFloat(checkbox.dataset.productCost || '0');
                    const isChecked = checkbox.checked;

                    if (row) {
                        row.style.display = isChecked ? 'flex' : 'none';
                    }

                    if (isChecked) {
                        selectedTotal += lineCost;
                        selectedCount += 1;
                    }
                });

                if (summaryRows.length && selectedCount === 0) {
                    summaryRows.forEach((row) => {
                        row.style.display = 'none';
                    });
                }

                if (totalValueElement) {
                    totalValueElement.textContent = formatCurrency(basePrice + selectedTotal);
                }
            };

            updateEstimate();
            productCheckboxes.forEach((checkbox) => {
                checkbox.addEventListener('change', updateEstimate);
            });
        })();
    </script>
    <script src="assets/js/main.js"></script>
</body>
</html>
