<?php
require __DIR__ . '/includes/functions.php';

$currentPage = 'reup';
$pageTitle = 'Re-Up Sofa Makeover | Furnify';
$serviceOptions = reup_service_options();
$conditionOptions = reup_condition_options();
$issueOptions = reup_issue_options();
$errors = array();
$csrfToken = csrf_token();
$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);
    $serviceType = clean_text((string) (isset($_POST['service_type']) ? $_POST['service_type'] : ''), 80);
    $condition = clean_text((string) (isset($_POST['condition_level']) ? $_POST['condition_level'] : ''), 80);
    $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'] : 1);
    $fabricPreference = clean_text((string) (isset($_POST['fabric_preference']) ? $_POST['fabric_preference'] : ''), 160);
    $message = clean_text((string) (isset($_POST['message']) ? $_POST['message'] : ''), 1000);
    $issues = isset($_POST['issues']) && is_array($_POST['issues']) ? $_POST['issues'] : array();
    $cleanIssues = array();
    foreach ($issues as $issue) {
        $issue = clean_text((string) $issue, 80);
        if (isset($issueOptions[$issue])) {
            $cleanIssues[] = $issue;
        }
    }

    if ($name === '') {
        $errors[] = 'Please enter your name.';
    }
    if ($phone === '') {
        $errors[] = 'Please enter your phone number.';
    }
    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    }
    if ($city === '') {
        $errors[] = 'Please enter your city.';
    }
    if (!isset($serviceOptions[$serviceType])) {
        $errors[] = 'Please choose a Re-Up service.';
    }
    if (!isset($conditionOptions[$condition])) {
        $errors[] = 'Please choose the sofa condition.';
    }
    if ($widthCm < 50 || $depthCm < 40) {
        $errors[] = 'Please enter realistic sofa width and depth in centimeters.';
    }
    if ($heightCm < 20) {
        $errors[] = 'Please enter realistic sofa height in centimeters.';
    }

    $upload = save_uploaded_reup_photo(isset($_FILES['sofa_photo']) ? $_FILES['sofa_photo'] : null);
    if (!$upload['ok']) {
        $errors[] = $upload['error'];
    }

    if (!$errors) {
        $estimate = calculate_reup_estimate($serviceType, $condition, $widthCm, $depthCm, $heightCm, $seatCount, $cleanIssues);
        $savedRequest = array(
            'request_number' => generate_reup_number(),
            'type' => 'reup',
            'status' => 'For review',
            'customer' => array(
                'name' => $name,
                'phone' => $phone,
                'email' => $email,
                'city' => $city,
                'address' => $address,
            ),
            'sofa' => array(
                'service_type' => $serviceType,
                'service_label' => $serviceOptions[$serviceType],
                'condition_level' => $condition,
                'condition_label' => $conditionOptions[$condition],
                'issues' => $cleanIssues,
                'width_cm' => $widthCm,
                'depth_cm' => $depthCm,
                'height_cm' => $heightCm,
                'seat_count' => $seatCount,
                'fabric_preference' => $fabricPreference,
                'photo_path' => $upload['path'],
            ),
            'estimate' => $estimate,
            'message' => $message,
            'created_at' => date('c'),
        );

        customer_attach_to_request($savedRequest);
        if (save_reup_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">
    <div class="container">
        <p class="eyebrow">Furnify Re-Up</p>
        <h1>Turn old sofas into a fresh premium piece.</h1>
        <p>Upload a clear photo, enter the sofa dimensions, and get a preliminary estimate range before our team confirms the final quotation.</p>
    </div>
</section>

<section class="reup-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">Request received</p>
                        <h2><?= e($savedRequest['request_number']) ?></h2>
                        <p class="lead">Preliminary Re-Up 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="reup.php" class="btn btn-outline-primary">Send Another Re-Up</a>
                    </div>
                    <div class="col-lg-5">
                        <div class="uploaded-preview">
                            <img src="<?= e($savedRequest['sofa']['photo_path']) ?>" alt="Uploaded sofa photo">
                        </div>
                    </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">AI-assisted estimate</p>
                            <h2>Request a Re-Up quotation</h2>
                            <p class="text-muted">This gives a preliminary range only. Final price will be confirmed after manual checking of actual condition, materials, 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">Address / pickup location</label><input class="form-control" name="address" value="<?= e(customer_form_value('address', '')) ?>"></div>

                            <div class="col-md-6">
                                <label class="form-label">Re-Up service *</label>
                                <select class="form-select" name="service_type" required>
                                    <option value="">Choose service</option>
                                    <?php foreach ($serviceOptions as $key => $label): ?>
                                        <option value="<?= e($key) ?>" <?= (isset($_POST['service_type']) && $_POST['service_type'] === $key) ? 'selected' : '' ?>><?= e($label) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Condition *</label>
                                <select class="form-select" name="condition_level" required>
                                    <option value="">Choose condition</option>
                                    <?php foreach ($conditionOptions as $key => $label): ?>
                                        <option value="<?= e($key) ?>" <?= (isset($_POST['condition_level']) && $_POST['condition_level'] === $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="50" 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="40" 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="20" 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="12" step="1" name="seat_count" value="<?= e(isset($_POST['seat_count']) ? $_POST['seat_count'] : '3') ?>"></div>

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

                            <div class="col-md-6"><label class="form-label">Preferred fabric / color</label><input class="form-control" name="fabric_preference" placeholder="Example: gray linen, brown leatherette" value="<?= e(isset($_POST['fabric_preference']) ? $_POST['fabric_preference'] : '') ?>"></div>
                            <div class="col-md-6"><label class="form-label">Upload sofa photo *</label><input class="form-control" type="file" name="sofa_photo" accept="image/jpeg,image/png,image/webp" required></div>
                            <div class="col-12"><label class="form-label">Notes</label><textarea class="form-control" name="message" rows="4" placeholder="Tell us what you want to change."><?= 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-magic" aria-hidden="true"></i> Generate Preliminary Estimate</button></div>
                        </form>
                    </div>
                </div>
                <div class="col-lg-5">
                    <div class="reup-info-card sticky-lg-top">
                        <p class="eyebrow">Better quoting flow</p>
                        <h2>Recommended process</h2>
                        <div class="reup-process">
                            <div><span>01</span><strong>Photo + dimensions</strong><p>Customer uploads sofa photo and exact width, depth, and height.</p></div>
                            <div><span>02</span><strong>Instant range</strong><p>System gives a preliminary estimate range using size, condition, and repair type.</p></div>
                            <div><span>03</span><strong>Manual confirmation</strong><p>Admin reviews the photo, sets final quote, and contacts the customer.</p></div>
                        </div>
                        <div class="alert alert-warning mb-0"><strong>Important:</strong> Do not show the estimate as final price. Re-Up work depends on actual frame, foam, fabric choice, and hidden damage.</div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

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