<?php
require __DIR__ . '/includes/functions.php';
start_secure_session();

$currentPage = 'custom';
$pageTitle = 'Custom Sofa Quote | Furnify';
$bodyClass = 'custom-page';

$typeOptions = custom_sofa_type_options();
$styleOptions = custom_style_options();
$materialOptions = custom_material_options();
$firmnessOptions = custom_firmness_options();
$featureOptions = custom_feature_options();
$csrfToken = csrf_token();
$errors = array();
$success = false;
$savedRequest = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token((string) (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : ''))) {
        $errors[] = 'Security token expired. Please refresh the page and try again.';
    }

    $name = clean_text((string) (isset($_POST['name']) ? $_POST['name'] : ''), 140);
    $phone = clean_text((string) (isset($_POST['phone']) ? $_POST['phone'] : ''), 40);
    $email = clean_text((string) (isset($_POST['email']) ? $_POST['email'] : ''), 180);
    $city = clean_text((string) (isset($_POST['city']) ? $_POST['city'] : ''), 140);
    $address = clean_text((string) (isset($_POST['address']) ? $_POST['address'] : ''), 255);
    $sofaType = (string) (isset($_POST['sofa_type']) ? $_POST['sofa_type'] : '');
    $designStyle = (string) (isset($_POST['design_style']) ? $_POST['design_style'] : '');
    $materialPreference = (string) (isset($_POST['material_preference']) ? $_POST['material_preference'] : '');
    $colorPreference = clean_text((string) (isset($_POST['color_preference']) ? $_POST['color_preference'] : ''), 140);
    $firmness = (string) (isset($_POST['firmness']) ? $_POST['firmness'] : '');
    $widthCm = (float) (isset($_POST['width_cm']) ? $_POST['width_cm'] : 0);
    $depthCm = (float) (isset($_POST['depth_cm']) ? $_POST['depth_cm'] : 0);
    $heightCm = (float) (isset($_POST['height_cm']) ? $_POST['height_cm'] : 0);
    $seatCount = (int) (isset($_POST['seat_count']) ? $_POST['seat_count'] : 3);
    $chaiseSide = clean_text((string) (isset($_POST['chaise_side']) ? $_POST['chaise_side'] : ''), 80);
    $budgetRange = clean_text((string) (isset($_POST['budget_range']) ? $_POST['budget_range'] : ''), 100);
    $timeline = clean_text((string) (isset($_POST['timeline']) ? $_POST['timeline'] : ''), 100);
    $message = clean_text((string) (isset($_POST['message']) ? $_POST['message'] : ''), 1600);
    $features = isset($_POST['features']) && is_array($_POST['features']) ? $_POST['features'] : array();
    $cleanFeatures = array();
    foreach ($features as $feature) {
        $feature = (string) $feature;
        if (isset($featureOptions[$feature])) {
            $cleanFeatures[] = $feature;
        }
    }

    if ($name === '') { $errors[] = 'Name is required.'; }
    if ($phone === '') { $errors[] = 'Phone is required.'; }
    if ($city === '') { $errors[] = 'City is required.'; }
    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = 'Please enter a valid email address.'; }
    if (!isset($typeOptions[$sofaType])) { $errors[] = 'Please choose a sofa type.'; }
    if (!isset($styleOptions[$designStyle])) { $errors[] = 'Please choose a design style.'; }
    if (!isset($materialOptions[$materialPreference])) { $errors[] = 'Please choose a material preference.'; }
    if (!isset($firmnessOptions[$firmness])) { $errors[] = 'Please choose cushion firmness.'; }
    if ($widthCm < 60 || $widthCm > 900) { $errors[] = 'Width should be between 60cm and 900cm.'; }
    if ($depthCm < 45 || $depthCm > 400) { $errors[] = 'Depth should be between 45cm and 400cm.'; }
    if ($heightCm < 30 || $heightCm > 180) { $errors[] = 'Height should be between 30cm and 180cm.'; }
    if ($seatCount < 1 || $seatCount > 14) { $errors[] = 'Seat count should be between 1 and 14.'; }
    if ($message === '' && empty($_FILES['inspiration_photo']['name'])) { $errors[] = 'Please add design notes or upload an inspiration photo.'; }

    $inspirationUpload = array('ok' => true, 'path' => '', 'error' => '');
    $roomUpload = array('ok' => true, 'path' => '', 'error' => '');
    if (!$errors) {
        $inspirationUpload = save_uploaded_custom_photo(isset($_FILES['inspiration_photo']) ? $_FILES['inspiration_photo'] : null, 'inspiration', false);
        if (!$inspirationUpload['ok']) { $errors[] = $inspirationUpload['error']; }
        $roomUpload = save_uploaded_custom_photo(isset($_FILES['room_photo']) ? $_FILES['room_photo'] : null, 'room', false);
        if (!$roomUpload['ok']) { $errors[] = $roomUpload['error']; }
    }

    if (!$errors) {
        $estimate = calculate_custom_sofa_estimate($sofaType, $designStyle, $materialPreference, $widthCm, $depthCm, $heightCm, $seatCount, $cleanFeatures);
        $savedRequest = array(
            'request_number' => generate_custom_quote_number(),
            'status' => 'For design review',
            'customer' => array(
                'name' => $name,
                'phone' => $phone,
                'email' => $email,
                'city' => $city,
                'address' => $address,
            ),
            'sofa' => array(
                'sofa_type' => $sofaType,
                'sofa_type_label' => $typeOptions[$sofaType],
                'design_style' => $designStyle,
                'design_style_label' => $styleOptions[$designStyle],
                'material_preference' => $materialPreference,
                'material_preference_label' => $materialOptions[$materialPreference],
                'color_preference' => $colorPreference,
                'firmness' => $firmness,
                'firmness_label' => $firmnessOptions[$firmness],
                'features' => $cleanFeatures,
                'width_cm' => $widthCm,
                'depth_cm' => $depthCm,
                'height_cm' => $heightCm,
                'seat_count' => $seatCount,
                'chaise_side' => $chaiseSide,
                'budget_range' => $budgetRange,
                'timeline' => $timeline,
                'inspiration_photo_path' => $inspirationUpload['path'],
                'room_photo_path' => $roomUpload['path'],
            ),
            'estimate' => $estimate,
            'message' => $message,
            'created_at' => date('c'),
        );

        customer_attach_to_request($savedRequest);
        if (save_custom_quote_request($savedRequest)) {
            $success = true;
        } else {
            $errors[] = 'Request was computed but could not be saved. Please contact the store admin.';
        }
    }
}

require __DIR__ . '/includes/header.php';
?>

<section class="page-hero mini-hero reup-hero custom-hero">
    <div class="container">
        <p class="eyebrow">Furnify Custom Sofa</p>
        <h1>Get a personalized sofa quote made for your space.</h1>
        <p>Send your preferred size, style, material, color, and reference photo. Furnify will generate a preliminary range, then our admin team will confirm the final quotation.</p>
    </div>
</section>

<section class="reup-section custom-section">
    <div class="container">
        <?php if ($success && $savedRequest): ?>
            <div class="reup-success-card">
                <div class="row g-4 align-items-center">
                    <div class="col-lg-7">
                        <p class="eyebrow">Custom request received</p>
                        <h2><?= e($savedRequest['request_number']) ?></h2>
                        <p class="lead">Preliminary custom sofa estimate:</p>
                        <div class="estimate-range"><?= money($savedRequest['estimate']['low']) ?> - <?= money($savedRequest['estimate']['high']) ?></div>
                        <p class="text-muted mb-4"><?= e($savedRequest['estimate']['note']) ?></p>
                        <a href="index.php" class="btn btn-primary">Back to Store</a>
                        <a href="custom-sofa.php" class="btn btn-outline-primary">Send Another Custom Request</a>
                    </div>
                    <div class="col-lg-5">
                        <?php if ($savedRequest['sofa']['inspiration_photo_path']): ?>
                            <div class="uploaded-preview"><img src="<?= e($savedRequest['sofa']['inspiration_photo_path']) ?>" alt="Uploaded custom sofa inspiration"></div>
                        <?php else: ?>
                            <div class="premium-mini-grid"><div><i class="bi bi-pencil-square" aria-hidden="true"></i><strong>Design notes saved</strong><span>Admin will review your preferred dimensions and details.</span></div></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <div class="col-lg-7">
                    <div class="form-card premium-form-card">
                        <div class="section-heading mb-3">
                            <p class="eyebrow">Made-to-order estimate</p>
                            <h2>Request a personalized sofa quotation</h2>
                            <p class="text-muted">This is a preliminary estimate only. Final price depends on approved drawing, actual fabric, foam, mechanism, production complexity, and delivery.</p>
                        </div>

                        <?php if ($errors): ?>
                            <div class="alert alert-danger">
                                <strong>Please check:</strong>
                                <ul class="mb-0">
                                    <?php foreach ($errors as $error): ?><li><?= e($error) ?></li><?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>

                        <form method="post" enctype="multipart/form-data" class="row g-3">
                            <input type="hidden" name="csrf_token" value="<?= e($csrfToken) ?>">
                            <div class="col-md-6"><label class="form-label">Name *</label><input class="form-control" name="name" required value="<?= e(customer_form_value('name', '')) ?>"></div>
                            <div class="col-md-6"><label class="form-label">Phone *</label><input class="form-control" name="phone" required value="<?= e(customer_form_value('phone', '')) ?>"></div>
                            <div class="col-md-6"><label class="form-label">Email</label><input class="form-control" type="email" name="email" value="<?= e(customer_form_value('email', '')) ?>"></div>
                            <div class="col-md-6"><label class="form-label">City *</label><input class="form-control" name="city" required value="<?= e(customer_form_value('city', '')) ?>"></div>
                            <div class="col-12"><label class="form-label">Delivery address / landmark</label><input class="form-control" name="address" value="<?= e(customer_form_value('address', '')) ?>"></div>

                            <div class="col-md-6">
                                <label class="form-label">Sofa type *</label>
                                <select class="form-select" name="sofa_type" required>
                                    <option value="">Choose sofa type</option>
                                    <?php foreach ($typeOptions as $key => $label): ?><option value="<?= e($key) ?>" <?= (isset($_POST['sofa_type']) && $_POST['sofa_type'] === $key) ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Design style *</label>
                                <select class="form-select" name="design_style" required>
                                    <option value="">Choose style</option>
                                    <?php foreach ($styleOptions as $key => $label): ?><option value="<?= e($key) ?>" <?= (isset($_POST['design_style']) && $_POST['design_style'] === $key) ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-3"><label class="form-label">Width cm *</label><input class="form-control" type="number" min="60" step="1" name="width_cm" required value="<?= e(isset($_POST['width_cm']) ? $_POST['width_cm'] : '') ?>"></div>
                            <div class="col-md-3"><label class="form-label">Depth cm *</label><input class="form-control" type="number" min="45" step="1" name="depth_cm" required value="<?= e(isset($_POST['depth_cm']) ? $_POST['depth_cm'] : '') ?>"></div>
                            <div class="col-md-3"><label class="form-label">Height cm *</label><input class="form-control" type="number" min="30" step="1" name="height_cm" required value="<?= e(isset($_POST['height_cm']) ? $_POST['height_cm'] : '') ?>"></div>
                            <div class="col-md-3"><label class="form-label">Seats *</label><input class="form-control" type="number" min="1" max="14" step="1" name="seat_count" required value="<?= e(isset($_POST['seat_count']) ? $_POST['seat_count'] : '3') ?>"></div>

                            <div class="col-md-6">
                                <label class="form-label">Material preference *</label>
                                <select class="form-select" name="material_preference" required>
                                    <option value="">Choose material</option>
                                    <?php foreach ($materialOptions as $key => $label): ?><option value="<?= e($key) ?>" <?= (isset($_POST['material_preference']) && $_POST['material_preference'] === $key) ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Cushion firmness *</label>
                                <select class="form-select" name="firmness" required>
                                    <option value="">Choose firmness</option>
                                    <?php foreach ($firmnessOptions as $key => $label): ?><option value="<?= e($key) ?>" <?= (isset($_POST['firmness']) && $_POST['firmness'] === $key) ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-6"><label class="form-label">Preferred color</label><input class="form-control" name="color_preference" placeholder="Example: cream, olive green, charcoal" value="<?= e(isset($_POST['color_preference']) ? $_POST['color_preference'] : '') ?>"></div>
                            <div class="col-md-6"><label class="form-label">Chaise side / orientation</label><input class="form-control" name="chaise_side" placeholder="Example: left chaise when facing sofa" value="<?= e(isset($_POST['chaise_side']) ? $_POST['chaise_side'] : '') ?>"></div>

                            <div class="col-12">
                                <label class="form-label">Add-ons / special features</label>
                                <div class="issue-grid">
                                    <?php foreach ($featureOptions as $key => $label): ?>
                                        <label><input type="checkbox" name="features[]" value="<?= e($key) ?>" <?= (isset($_POST['features']) && is_array($_POST['features']) && in_array($key, $_POST['features'], true)) ? 'checked' : '' ?>> <?= e($label) ?></label>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="col-md-6"><label class="form-label">Budget range</label><input class="form-control" name="budget_range" placeholder="Example: ₱30k-₱50k" value="<?= e(isset($_POST['budget_range']) ? $_POST['budget_range'] : '') ?>"></div>
                            <div class="col-md-6"><label class="form-label">Target timeline</label><input class="form-control" name="timeline" placeholder="Example: within 2 weeks" value="<?= e(isset($_POST['timeline']) ? $_POST['timeline'] : '') ?>"></div>
                            <div class="col-md-6"><label class="form-label">Inspiration photo</label><input class="form-control" type="file" name="inspiration_photo" accept="image/jpeg,image/png,image/webp"><div class="form-text">Optional, but recommended.</div></div>
                            <div class="col-md-6"><label class="form-label">Room / space photo</label><input class="form-control" type="file" name="room_photo" accept="image/jpeg,image/png,image/webp"><div class="form-text">Optional, helps with fit and style.</div></div>
                            <div class="col-12"><label class="form-label">Design notes *</label><textarea class="form-control" name="message" rows="5" placeholder="Describe the sofa you want: arm style, back height, leg style, comfort, fabric, sample link, or any special request."><?= e(isset($_POST['message']) ? $_POST['message'] : '') ?></textarea></div>
                            <div class="col-12"><button class="btn btn-primary btn-lg" type="submit"><i class="bi bi-pencil-square" aria-hidden="true"></i> Generate Custom Quote Range</button></div>
                        </form>
                    </div>
                </div>
                <div class="col-lg-5">
                    <div class="reup-info-card sticky-lg-top">
                        <p class="eyebrow">Better custom flow</p>
                        <h2>Recommended process</h2>
                        <div class="reup-process">
                            <div><span>01</span><strong>Customer sends idea</strong><p>Size, style, fabric, reference photo, and room photo if available.</p></div>
                            <div><span>02</span><strong>Preliminary range</strong><p>System gives a guide price using dimensions, material, type, and add-ons.</p></div>
                            <div><span>03</span><strong>Design confirmation</strong><p>Admin contacts customer, confirms final specs, and sets the final quotation.</p></div>
                        </div>
                        <div class="alert alert-warning mb-0"><strong>Important:</strong> Do not treat this as final price. Custom sofa pricing depends on approved design, fabric availability, mechanism, foam, and delivery details.</div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

<?php require __DIR__ . '/includes/footer.php'; ?>
