<?php
// request.php - Customer ticket request form with CX account auto-fill.
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['customer_id'])) {
    header('Location: ../login.php');
    exit;
}

require_once '../config/database.php';
require_once '../config/location_validator.php';
require_once '../includes/app_helpers.php';

function cx_request_state_for_select($state) {
    $state = trim((string)$state);
    $map = [
        'AL'=>'Alabama','ALABAMA'=>'Alabama',
        'AR'=>'Arkansas','ARKANSAS'=>'Arkansas',
        'FL'=>'Florida','FLORIDA'=>'Florida',
        'GA'=>'Georgia','GEORGIA'=>'Georgia',
        'IL'=>'Illinois','ILLINOIS'=>'Illinois',
        'IN'=>'Indiana','INDIANA'=>'Indiana',
        'KY'=>'Kentucky','KENTUCKY'=>'Kentucky',
        'LA'=>'Louisiana','LOUISIANA'=>'Louisiana',
        'MS'=>'Mississippi','MISSISSIPPI'=>'Mississippi',
        'MO'=>'Missouri','MISSOURI'=>'Missouri',
        'NC'=>'North Carolina','NORTH CAROLINA'=>'North Carolina',
        'OK'=>'Oklahoma','OKLAHOMA'=>'Oklahoma',
        'SC'=>'South Carolina','SOUTH CAROLINA'=>'South Carolina',
        'TN'=>'Tennessee','TENNESSEE'=>'Tennessee',
        'TX'=>'Texas','TEXAS'=>'Texas',
        'VA'=>'Virginia','VIRGINIA'=>'Virginia'
    ];
    return $map[strtoupper($state)] ?? $state;
}

$database = new Database();
$db = $database->getConnection();
$validator = new LocationValidator($db);

try {
    ensureAddressAndCallQueueTables($db);
    ensureOperationalTables($db);
    ensureUnifiedTicketWorkflow($db);
} catch (Throwable $e) {
    error_log('CX request setup warning: ' . $e->getMessage());
}

// Fetch the logged-in customer profile so the CX request form auto-fills from registration/account data.
$customerProfile = [];
try {
    $profileStmt = $db->prepare("SELECT c.*, ci.city_name AS registered_city_name, ci.state AS registered_city_state, ci.region AS registered_city_region
                                FROM customers c
                                LEFT JOIN cities ci ON ci.id = c.city_id
                                WHERE c.id = :id
                                LIMIT 1");
    $profileStmt->execute([':id' => $_SESSION['customer_id']]);
    $customerProfile = $profileStmt->fetch(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    error_log('CX request profile prefill warning: ' . $e->getMessage());
}

$zipMeta = null;
if (!empty($customerProfile['zip_code'])) {
    try {
        $zipMeta = getZipAddressMeta($db, (string)$customerProfile['zip_code']);
    } catch (Throwable $e) {
        $zipMeta = null;
    }
}

$prefillFullName = trim(($customerProfile['first_name'] ?? '') . ' ' . ($customerProfile['last_name'] ?? ''));
$prefillEmail    = trim((string)($customerProfile['email'] ?? ($_SESSION['customer_email'] ?? '')));
$prefillPhone    = trim((string)($customerProfile['phone_number'] ?? ''));
$prefillAddress  = trim((string)($customerProfile['address'] ?? ''));
$prefillZip      = trim((string)($customerProfile['zip_code'] ?? ''));
$prefillCity     = trim((string)($zipMeta['city_name'] ?? ($customerProfile['registered_city_name'] ?? '')));
$prefillCityId   = (string)($zipMeta['city_id'] ?? ($customerProfile['city_id'] ?? ''));
$prefillState    = cx_request_state_for_select($zipMeta['state'] ?? ($customerProfile['state'] ?? ($customerProfile['registered_city_state'] ?? '')));
$prefillRegion   = trim((string)($zipMeta['region'] ?? ($customerProfile['region'] ?? ($customerProfile['registered_city_region'] ?? ''))));

$warranty_types = ['Manufacturer Warranty', 'Extended Warranty', 'Home Warranty', 'Out of Warranty', 'Unknown'];
$state_options = ['Alabama','Arkansas','Florida','Georgia','Illinois','Indiana','Kentucky','Louisiana','Mississippi','Missouri','North Carolina','Oklahoma','South Carolina','Tennessee','Texas','Virginia'];

// Fetch data for dropdowns
$brands = $db->query("SELECT * FROM brands ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$appliance_types = $db->query("SELECT * FROM appliance_types ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$cities = $validator->getActiveCities();
$serviceable_areas = $validator->getAllServiceableAreasGrouped();
// Developer's Note: Dito natin kinukuha yung brands and appliance types para sa dropdown menu dynamically.

$pageTitle  = 'Request Service';
$activePage = 'request';
$notifCount = 0;
include __DIR__ . '/includes/header.php';
?>
<style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            margin-bottom: 70px;
        }
        
        .app-header {
            background-color: white;
            padding: 12px 16px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        
        .header-content {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .back-btn {
            background: none;
            border: none;
            font-size: 24px;
            color: #333;
            padding: 0;
            cursor: pointer;
        }
        
        .header-title {
            font-weight: 600;
            font-size: 18px;
            color: #333;
            margin: 0;
        }
        
        .form-container {
            padding: 20px 16px;
        }
        
        .form-section {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e3f2fd;
            cursor: pointer;
        }
        
        .form-label {
            font-size: 14px;
            font-weight: 500;
            color: #34495e;
            margin-bottom: 5px;
        }

        .form-control,
        .form-select {
            border-radius: 10px;
            border: 1px solid #dee2e6;
            padding: 12px 15px;
            font-size: 15px;
        }
        
        .form-control:focus,
        .form-select:focus {
            border-color: #3498db;
            box-shadow: 0 0 0 0.2rem rgba(52,152,219,0.25);
        }
        
        .optional-text {
            font-size: 12px;
            color: #95a5a6;
            margin-left: 5px;
        }
        
        .submit-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 16px;
            margin: 20px 0;
            transition: transform 0.2s;
        }
        
        .submit-btn:hover:not(:disabled) {
            transform: translateY(-2px);
        }
        
        .submit-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .alert {
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .zip-validation {
            margin-top: 10px;
            padding: 10px;
            border-radius: 8px;
            display: none;
        }
        
        .zip-valid {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .zip-invalid {
            background-color: #e4d941;
            color: #000000;
            border: 1px solid #f5c6cb;
        }
        
        .zip-checking {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeeba;
        }
        
        .serviceable-areas {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-top: 10px;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .city-group {
            margin-bottom: 15px;
        }
        
        .city-name {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 5px;
            padding-bottom: 5px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .area-badge {
            background-color: #e3f2fd;
            color: #1976d2;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            margin: 3px;
            display: inline-block;
        }
        
        .dropdown-with-manual {
            position: relative;
            color: #000000;
        }
        
        .not-listed-checkbox {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 8px;
            border-left: 3px solid #3498db;
        }
        
        .not-listed-checkbox .form-check {
            margin-bottom: 0;
        }
        
        .manual-input {
            margin-top: 10px;
            display: none;
        }
        
        .manual-input.show {
            display: block;
            animation: fadeIn 0.3s ease-in-out;
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .manual-input .input-group {
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        
        .manual-input .form-control {
            border-right: none;
        }
        
        .manual-input .input-group-text {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
        }
        
        .upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 15px;
            padding: 30px;
            text-align: center;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 20px;
        }
        
        .upload-area:hover {
            border-color: #667eea;
            background: #e3f2fd;
        }
        
        .upload-area i {
            font-size: 48px;
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .upload-area p {
            margin-bottom: 5px;
            color: #2c3e50;
        }
        
        .upload-area small {
            color: #95a5a6;
        }
        
        .image-preview-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        
        .preview-card {
            position: relative;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            aspect-ratio: 1;
        }
        
        .preview-card img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            cursor: pointer;
            transition: transform 0.3s;
        }
        
        .preview-card img:hover {
            transform: scale(1.05);
        }
        
        .remove-image {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 30px;
            height: 30px;
            background: rgba(231, 76, 60, 0.9);
            color: white;
            border: none;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
            z-index: 10;
        }
        
        .remove-image:hover {
            background: #c0392b;
            transform: scale(1.1);
        }
        
        .image-counter {
            font-size: 14px;
            color: #667eea;
            font-weight: 600;
            margin-top: 10px;
        }
        
        .lb-loader {
            display: none;
        }
        
        .lb-close {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0,0,0,0.5);
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            font-size: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 10000;
        }
        
        .lb-close:hover {
            background: rgba(0,0,0,0.8);
        }
        
        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            display: flex;
            justify-content: space-around;
            padding: 10px 0;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        }
        
        .nav-item {
            text-align: center;
            color: #95a5a6;
            text-decoration: none;
            font-size: 12px;
        }
        
        .nav-item.active {
            color: #3498db;
        }
        
        .nav-item i {
            font-size: 22px;
            display: block;
            margin-bottom: 4px;
        }
        
        .loader {
            border: 3px solid #f3f3f3;
            border-radius: 50%;
            border-top: 3px solid #3498db;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-right: 10px;
        }
        
        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }
        
        .auto-filled {
            background-color: #e8f5e8 !important;
            border-color: #28a745 !important;
        }
        
        select:disabled {
            background-color: #e9ecef !important;
            opacity: 0.8;
            cursor: not-allowed;
        }
        
        .upload-area p {
            color: white !important;
            font-weight: 600 !important;
        }

        .upload-area small {
            color: white !important;
        }

        .image-counter {
            color: #dbeafe !important;
        }


        /* CX request section title font only */
        .cx-section-title-white,
        .cx-section-title-white i {
            color: #ffffff !important;
        }

        .modal-title {
            color: #0f172a !important;
        }

        .toast-header strong,
        .toast-body {
            color: #0f172a !important;
        }


        /* Force CX request form text to white and keep address fields editable-looking */
        .form-container,
        .form-container label,
        .form-container .form-label,
        .form-container .form-text,
        .form-container .optional-text,
        .form-container p,
        .form-container small,
        .form-container span,
        .form-container .section-title,
        .form-container .section-title i {
            color: #ffffff !important;
        }

        .form-container .form-check-label {
        color: #000000 !important;
        }

        .form-container input,
        .form-container textarea,
        .form-container select,
        .form-container .form-control,
        .form-container .form-select,
        .form-container .input-group-text {
            color: #ffffff !important;
            background-color: rgba(15, 23, 42, 0.86) !important;
            border-color: rgba(147, 197, 253, 0.55) !important;
        }

        .form-container input::placeholder,
        .form-container textarea::placeholder {
            color: rgba(255,255,255,.65) !important;
        }

        .form-container select option {
            color: #ffffff !important;
            background: #0f172a !important;
        }

        .auto-filled {
            background-color: rgba(30, 58, 138, 0.55) !important;
            border-color: rgba(147, 197, 253, 0.75) !important;
            color: #ffffff !important;
        }
    </style>

    <div class="form-container">
        <form id="requestForm" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="city_id" id="hidden_city_id" value="<?php echo h($prefillCityId); ?>">
            <input type="hidden" name="manual_brand" id="manual_brand" value="">
            <input type="hidden" name="manual_appliance_type" id="manual_appliance_type" value="">
            <input type="hidden" name="source" value="CX Submission">
            <input type="hidden" name="ticket_source" value="cx_online">

            <div class="form-section">
                <h3 class="section-title cx-section-title-white">
                    <i class="fas fa-user me-2"></i>
                    Customer Information
                </h3>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Ticket No</label>
                        <input type="text" class="form-control" value="Auto-generated after submit" readonly>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Source</label>
                        <input type="text" class="form-control" value="CX Submission" readonly>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">Name <span class="text-danger">*</span></label>
                    <input type="text" name="full_name" class="form-control auto-filled" value="<?php echo h($prefillFullName); ?>" placeholder="Customer name" required>
                    <small class="form-text text-muted">Auto-filled from the logged-in customer account.</small>
                </div>

                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Primary Phone <span class="text-danger">*</span></label>
                        <input type="tel" name="phone_number" class="form-control auto-filled" value="<?php echo h($prefillPhone); ?>" placeholder="e.g., 404-555-0123" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Secondary Phone <span class="optional-text">(Optional)</span></label>
                        <input type="tel" name="secondary_phone" class="form-control" placeholder="Alternative phone number">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Email <span class="text-danger">*</span></label>
                        <input type="email" name="customer_email" class="form-control auto-filled" value="<?php echo h($prefillEmail); ?>" placeholder="customer@email.com" required>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">Address <span class="text-danger">*</span></label>
                    <textarea name="service_address" class="form-control auto-filled" rows="2" placeholder="Street address, P.O. box, company name" required><?php echo h($prefillAddress); ?></textarea>
                </div>

                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label">City <span class="text-danger">*</span></label>
                        <input type="text" name="city_display" id="city_display" class="form-control auto-filled" value="<?php echo h($prefillCity); ?>" placeholder="Auto-filled by ZIP" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">ZIP Code <span class="text-danger">*</span></label>
                        <input type="text" name="zip_code" id="zip_code" class="form-control auto-filled" value="<?php echo h($prefillZip); ?>" maxlength="5" pattern="\d{5}" placeholder="xxxxx" required>
                        <div id="zipValidationMessage" class="zip-validation"></div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">State <span class="text-danger">*</span></label>
                        <select name="state" id="state_select" class="form-select" required>
                            <option value="">Select State</option>
                            <?php foreach($state_options as $stateOption): ?>
                                <option value="<?php echo h($stateOption); ?>" <?php echo ($prefillState === $stateOption) ? 'selected' : ''; ?>><?php echo h($stateOption); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Region</label>
                        <input type="text" name="region" id="region_display" class="form-control auto-filled" value="<?php echo h($prefillRegion); ?>" placeholder="Auto-filled by ZIP">
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">Address Note <span class="optional-text">(Optional)</span></label>
                    <textarea name="service_address_2" class="form-control" rows="3" placeholder="Apartment, suite, gate code, building, floor, landmark, or delivery/service note"></textarea>
                </div>
            </div>

            <div class="form-section">
                <h3 class="section-title cx-section-title-white">
                    <i class="fas fa-box-open me-2"></i>
                    Product Information
                </h3>

                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Model <span class="text-danger">*</span></label>
                        <input type="text" name="model_number" class="form-control" placeholder="e.g., RF28R7201SR" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Serial <span class="text-danger">*</span></label>
                        <input type="text" name="serial_number" class="form-control" placeholder="e.g., X3Z9Y7" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Model Version <span class="optional-text">(Optional)</span></label>
                        <input type="text" name="product_model_version" class="form-control" placeholder="e.g., Version 2 / Series A">
                    </div>
                </div>

                <div class="mb-3 dropdown-with-manual">
                    <label class="form-label">Brand <span class="text-danger">*</span></label>
                    <select name="brand_id" id="brand_select" class="form-select" required>
                        <option value="">Select Brand</option>
                        <?php foreach($brands as $brand): ?>
                            <option value="<?php echo (int)$brand['id']; ?>"><?php echo h($brand['name']); ?></option>
                        <?php endforeach; ?>
                    </select>

                    <div class="not-listed-checkbox">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="brand_not_listed">
                            <label class="form-check-label" for="brand_not_listed">
                                My brand is not listed
                            </label>
                        </div>
                    </div>

                    <div class="manual-input" id="brand_manual_input">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-tag"></i></span>
                            <input type="text" class="form-control" id="brand_manual" placeholder="Enter brand name">
                        </div>
                    </div>
                </div>

                <div class="mb-3 dropdown-with-manual">
                    <label class="form-label">Product Category <span class="text-danger">*</span></label>
                    <select name="appliance_type_id" id="appliance_type_select" class="form-select" required>
                        <option value="">Select Category</option>
                        <?php foreach($appliance_types as $type): ?>
                            <option value="<?php echo (int)$type['id']; ?>" <?php echo (@$_GET['type'] == $type['id']) ? 'selected' : ''; ?>><?php echo h($type['name']); ?></option>
                        <?php endforeach; ?>
                    </select>

                    <div class="not-listed-checkbox">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="appliance_type_not_listed">
                            <label class="form-check-label" for="appliance_type_not_listed">
                                My product category is not listed
                            </label>
                        </div>
                    </div>

                    <div class="manual-input" id="appliance_type_manual_input">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-tools"></i></span>
                            <input type="text" class="form-control" id="appliance_type_manual" placeholder="Enter product category">
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Purchase Date <span class="optional-text">(Optional)</span></label>
                        <input type="date" name="purchase_date" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Warranty Type <span class="text-danger">*</span></label>
                        <select name="warranty_type" class="form-select" required>
                            <option value="">Select Warranty Type</option>
                            <?php foreach($warranty_types as $warranty): ?>
                                <option value="<?php echo h($warranty); ?>"><?php echo h($warranty); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <div class="form-section">
                <h3 class="section-title cx-section-title-white">
                    <i class="fas fa-clock me-2"></i>
                    Service Details
                </h3>


                <div class="mb-3">
                    <label class="form-label">Cx Preferred Date <span class="text-danger">*</span></label>
                    <input type="date" name="preferred_date" id="preferred_date" class="form-control" required min="<?php echo date('Y-m-d'); ?>">
                </div>

                <div class="mb-3">
                    <label class="form-label">
                        Problem Description <span class="text-danger">*</span>
                    </label>
                    <textarea name="issue_description" class="form-control" rows="3" placeholder="Please describe the issue with your appliance..." required></textarea>
                </div>

                <div class="mb-3">
                    <label class="form-label">
                        Special Request <span class="optional-text text-white-optional">(Optional)</span>
                    </label>
                    <textarea name="special_request" class="form-control" rows="3" placeholder="Please describe any special requests or instructions..."></textarea>
                </div>
            </div>

            <div class="form-section">
                <h3 class="section-title">
                    <i class="fas fa-camera me-2"></i>
                    Upload Photos <span class="optional-text">(Optional)</span>
                </h3>
                
                <div class="upload-area" id="uploadArea">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <p>Click to upload or drag and drop</p>
                    <small>Supported formats: JPG, PNG, GIF, WEBP (Max 5MB each)</small>
                </div>
                
                <input type="file" id="fileInput" name="images[]" multiple accept="image/jpeg,image/png,image/gif,image/webp" style="display: none;">
                
                <div class="image-preview-container" id="imagePreview"></div>
                <div class="image-counter" id="imageCounter">0 images selected</div>
            </div>
            
            <button type="submit" class="submit-btn" id="submitBtn" disabled>
                <i class="fas fa-paper-plane me-2"></i>
                Submit Request
            </button>
        </form>
    </div>

    <div class="modal fade" id="imageZoomModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Image Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <img src="" id="zoomedImage" class="img-fluid" style="max-height: 70vh;">
                </div>
            </div>
        </div>
    </div>

    <nav class="bottom-nav">
        <a href="dashboard.php" class="nav-item">
            <i class="fas fa-home"></i>
            <span>Home</span>
        </a>
        <a href="request.php" class="nav-item active">
            <i class="fas fa-plus-circle"></i>
            <span>Request</span>
        </a>
        <a href="my_requests.php" class="nav-item">
            <i class="fas fa-clipboard-list"></i>
            <span>My Requests</span>
        </a>
        <a href="messages.php" class="nav-item">
            <i class="fas fa-comments"></i>
            <span>Messages</span>
        </a>
        <a href="profile.php" class="nav-item">
            <i class="fas fa-user"></i>
            <span>Profile</span>
        </a>
    </nav>

    <div class="toast-container position-fixed bottom-0 end-0 p-3">
        <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <strong class="me-auto" id="toastTitle">Notification</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body" id="toastMessage"></div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    let isValidZip = false;
    let zipCheckTimer;
    let currentCityId = null;
    let selectedFiles = [];
    const MAX_FILE_SIZE = 5 * 1024 * 1024;
    
    $(document).ready(function() {
        $('#brand_not_listed').change(function() {
            const isChecked = $(this).is(':checked');
            const $brandSelect = $('#brand_select');
            const $brandManual = $('#brand_manual_input');
            
            if(isChecked) {
                $brandSelect.prop('disabled', true).val('').prop('required', false);
                $brandManual.addClass('show');
                $('#brand_manual').prop('required', true);
            } else {
                $brandSelect.prop('disabled', false).prop('required', true);
                $brandManual.removeClass('show');
                $('#brand_manual').prop('required', false).val('');
                $('#manual_brand').val('');
            }
            validateForm();
        });
        
        $('#appliance_type_not_listed').change(function() {
            const isChecked = $(this).is(':checked');
            const $typeSelect = $('#appliance_type_select');
            const $typeManual = $('#appliance_type_manual_input');
            
            if(isChecked) {
                $typeSelect.prop('disabled', true).val('').prop('required', false);
                $typeManual.addClass('show');
                $('#appliance_type_manual').prop('required', true);
            } else {
                $typeSelect.prop('disabled', false).prop('required', true);
                $typeManual.removeClass('show');
                $('#appliance_type_manual').prop('required', false).val('');
                $('#manual_appliance_type').val('');
            }
            validateForm();
        });
        
        $('#brand_manual').on('input', function() {
            $('#manual_brand').val($(this).val());
            validateForm();
        });
        
        $('#appliance_type_manual').on('input', function() {
            $('#manual_appliance_type').val($(this).val());
            validateForm();
        });
        
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#667eea';
            uploadArea.style.background = '#e3f2fd';
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.style.borderColor = '#dee2e6';
            uploadArea.style.background = '#f8f9fa';
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#dee2e6';
            uploadArea.style.background = '#f8f9fa';
            const files = Array.from(e.dataTransfer.files);
            handleFiles(files);
        });
        
        fileInput.addEventListener('change', (e) => {
            const files = Array.from(e.target.files);
            handleFiles(files);
        });
        
        $('#zip_code').on('input', function() {
            clearTimeout(zipCheckTimer);

            let zip = $(this).val().replace(/\D/g, '').substring(0, 5);
            $(this).val(zip);

            if(zip.length === 5) {
                checkZipCode(zip);
            } else {
                $('#zipValidationMessage')
                    .removeClass('zip-valid zip-invalid zip-checking')
                    .hide();

                $('#city_display')
                    .removeClass('auto-filled')
                    .val('')
                    .prop('disabled', false);

                $('#state_select')
                    .removeClass('auto-filled')
                    .val('')
                    .prop('disabled', false);
                $('#region_display').removeClass('auto-filled').val('');

                $('#hidden_city_id').val('');

                isValidZip = false;
                currentCityId = null;

                validateForm();
            }
        });
        
        $('#city_display').on('change', function() {
            if($(this).val()) {
                $('#hidden_city_id').val($(this).val());
                if(!isValidZip) {
                    let zip = $('#zip_code').val();
                    if(zip.length === 5) {
                        checkZipCode(zip);
                    }
                }
            } else {
                $('#hidden_city_id').val('');
            }
            validateForm();
        });
        
        
        $('input[name="full_name"], input[name="phone_number"], input[name="secondary_phone"], input[name="customer_email"], input[name="model_number"], input[name="serial_number"], input[name="product_model_version"], input[name="purchase_date"]').on('input change', function() {
            validateForm();
        });
        
        $('textarea[name="service_address"], textarea[name="service_address_2"], textarea[name="issue_description"], textarea[name="special_request"]').on('input', function() {
            validateForm();
        });
        
        $('select[name="brand_id"], select[name="appliance_type_id"], select[name="warranty_type"], select[name="state"]').on('change', function() {
            validateForm();
        });
        
        $('#preferred_date').on('change', function() {
            validateForm();
        });
        
        $('#requestForm').on('submit', function(e) {
            e.preventDefault();
            
            if(!isValidZip) {
                showToast('Please enter a valid serviceable ZIP code', 'error');
                return;
            }
            
            if(currentCityId && $('#hidden_city_id').val() != currentCityId) {
                showToast('The selected city does not match the ZIP code. Please use the auto-filled city.', 'error');
                return;
            }
            
            const selectedDate = new Date($('#preferred_date').val());
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            
            if(selectedDate < today) {
                showToast('Preferred date cannot be in the past', 'error');
                return;
            }
            
            
            if(!$('#brand_not_listed').is(':checked') && !$('#brand_select').val()) {
                showToast('Please select a brand', 'error');
                return;
            }
            
            if($('#brand_not_listed').is(':checked') && !$('#brand_manual').val().trim()) {
                showToast('Please enter your brand name', 'error');
                return;
            }
            
            if(!$('#appliance_type_not_listed').is(':checked') && !$('#appliance_type_select').val()) {
                showToast('Please select an appliance type', 'error');
                return;
            }
            
            if($('#appliance_type_not_listed').is(':checked') && !$('#appliance_type_manual').val().trim()) {
                showToast('Please enter your appliance type', 'error');
                return;
            }
            
            submitForm();
        });
        
        const initialZip = $('#zip_code').val().replace(/\D/g, '').substring(0, 5);
        if(initialZip.length === 5) {
            $('#zip_code').val(initialZip);
            checkZipCode(initialZip);
        } else {
            validateForm();
        }
    });
    
    
    function handleFiles(files) {
        for(let file of files) {
            if(!file.type.startsWith('image/')) {
                showToast(`${file.name} is not an image file`, 'error');
                continue;
            }
            
            if(file.size > MAX_FILE_SIZE) {
                showToast(`${file.name} exceeds 5MB limit`, 'error');
                continue;
            }
            
            const isDuplicate = selectedFiles.some(f => f.name === file.name && f.size === file.size);
            if(!isDuplicate) {
                selectedFiles.push(file);
            }
        }
        updatePreview();
    }
    
    function updatePreview() {
        const previewContainer = document.getElementById('imagePreview');
        const counter = document.getElementById('imageCounter');
        
        previewContainer.innerHTML = '';
        
        selectedFiles.forEach((file, index) => {
            const reader = new FileReader();
            
            reader.onload = (e) => {
                const previewCard = document.createElement('div');
                previewCard.className = 'preview-card';
                
                const img = document.createElement('img');
                img.src = e.target.result;
                img.alt = `Preview ${index + 1}`;
                img.onclick = () => zoomImage(e.target.result);
                
                const removeBtn = document.createElement('button');
                removeBtn.className = 'remove-image';
                removeBtn.innerHTML = '<i class="fas fa-times"></i>';
                removeBtn.onclick = (e) => {
                    e.stopPropagation();
                    removeImage(index);
                };
                
                previewCard.appendChild(img);
                previewCard.appendChild(removeBtn);
                previewContainer.appendChild(previewCard);
            };
            
            reader.readAsDataURL(file);
        });
        
        counter.textContent = `${selectedFiles.length} image${selectedFiles.length !== 1 ? 's' : ''} selected`;
        updateFileInput();
    }
    
    function removeImage(index) {
        selectedFiles.splice(index, 1);
        updatePreview();
        validateForm();
    }
    
    function updateFileInput() {
        const fileInput = document.getElementById('fileInput');
        const dataTransfer = new DataTransfer();
        
        selectedFiles.forEach(file => {
            dataTransfer.items.add(file);
        });
        
        fileInput.files = dataTransfer.files;
    }
    
    function zoomImage(src) {
        const modal = new bootstrap.Modal(document.getElementById('imageZoomModal'));
        document.getElementById('zoomedImage').src = src;
        modal.show();
    }
    
    function checkZipCode(zip) {
        $('#zipValidationMessage')
            .removeClass('zip-valid zip-invalid')
            .addClass('zip-checking')
            .html('<div class="loader"></div> Checking service availability...')
            .show();
        
        $.ajax({
            url: 'check_zip.php',
            method: 'POST',
            data: { zip_code: zip },
            dataType: 'json',
            success: function(response) {
                if(response.serviceable) {
                        $('#zipValidationMessage')
                            .removeClass('zip-valid zip-invalid zip-checking')
                            .empty()
                            .hide();
                    
                    if(response.city_id) {
                        $('#city_display').val(response.city_name || response.city || '').addClass('auto-filled');
                        $('#hidden_city_id').val(response.city_id);
                        currentCityId = response.city_id;
                    }

                    if(response.region) {
                        $('#region_display').val(response.region).addClass('auto-filled');
                    }

                    if(response.state) {
                        let stateMap = {
                            'AL': 'Alabama',
                            'AR': 'Arkansas',
                            'FL': 'Florida',
                            'GA': 'Georgia',
                            'IL': 'Illinois',
                            'IN': 'Indiana',
                            'KY': 'Kentucky',
                            'LA': 'Louisiana',
                            'MS': 'Mississippi',
                            'MO': 'Missouri',
                            'NC': 'North Carolina',
                            'OK': 'Oklahoma',
                            'SC': 'South Carolina',
                            'TN': 'Tennessee',
                            'TX': 'Texas',
                            'VA': 'Virginia'
                        };

                        let fullState = stateMap[response.state] || response.state;

                        $('#state_select').val(fullState)
                            .addClass('auto-filled')
                            .prop('disabled', false);
                    }

                    isValidZip = true;
                } else {
                    $('#zipValidationMessage')
                        .removeClass('zip-checking zip-valid')
                        .addClass('zip-invalid')
                        .html('<i class="fas fa-exclamation-circle me-2"></i>' + response.message);
                    
                    $('#city_display').removeClass('auto-filled').val('');
                    $('#state_select').removeClass('auto-filled').val('').prop('disabled', false);
                    $('#region_display').removeClass('auto-filled').val('');
                    $('#hidden_city_id').val('');
                    isValidZip = false;
                    currentCityId = null;
                }
                validateForm();
            },
            error: function() {
                $('#zipValidationMessage')
                    .removeClass('zip-checking')
                    .addClass('zip-invalid')
                    .html('<i class="fas fa-exclamation-circle me-2"></i> Error checking ZIP code');

                $('#city_display')
                    .removeClass('auto-filled')
                    .val('')
                    .prop('disabled', false);

                $('#state_select')
                    .removeClass('auto-filled')
                    .val('')
                    .prop('disabled', false);
                $('#region_display').removeClass('auto-filled').val('');

                $('#hidden_city_id').val('');

                isValidZip = false;
                currentCityId = null;

                validateForm();
            }
        });
    }
    
    function submitForm() {
        if (!document.querySelector('input[name="submit_token"]')) {
            let tokenInput = document.createElement('input');
            tokenInput.type = 'hidden';
            tokenInput.name = 'submit_token';
            tokenInput.value = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            document.getElementById('requestForm').appendChild(tokenInput);
        }
        
        let formData = new FormData(document.getElementById('requestForm'));
        
        selectedFiles.forEach((file, index) => {
            formData.append('images[]', file);
        });
        
        $('#submitBtn').prop('disabled', true).html('<span class="loader"></span> Submitting...');
        
        $.ajax({
            url: 'process_request.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if(response.success) {
                    showToast(response.message, 'success');
                    $('#requestForm')[0].reset();
                    $('#zipValidationMessage').hide();
                    $('#city_display').removeClass('auto-filled').val('');
                    $('#state_select').removeClass('auto-filled').val('').prop('disabled', false);
                    $('#region_display').removeClass('auto-filled').val('');
                    $('#hidden_city_id').val('');
                    selectedFiles = [];
                    updatePreview();
                    isValidZip = false;
                    currentCityId = null;
                    
                    $('#brand_not_listed').prop('checked', false).change();
                    $('#appliance_type_not_listed').prop('checked', false).change();
                    
                    validateForm();
                    
                    setTimeout(function() {
                        if(response.data && response.data.is_logged_in) {
                            window.location.href = 'dashboard.php';
                        } else {
                            window.location.href = 'index.php';
                        }
                    }, 2000);
                } else {
                    showToast(response.message, 'error');
                    $('#submitBtn').prop('disabled', false).html('<i class="fas fa-paper-plane me-2"></i> Submit Request');
                }
            },
            error: function(xhr, status, error) {
                console.log(xhr.responseText);
                showToast('Error submitting request. Please try again.', 'error');
                $('#submitBtn').prop('disabled', false).html('<i class="fas fa-paper-plane me-2"></i> Submit Request');
            }
        });
    }
    
    function validateForm() {
        const zipValid = isValidZip && $('#hidden_city_id').val();
        
        let brandValid;
        if($('#brand_not_listed').is(':checked')) {
            brandValid = $('#brand_manual').val().trim() !== '';
        } else {
            brandValid = $('#brand_select').val() !== '';
        }
        
        let typeValid;
        if($('#appliance_type_not_listed').is(':checked')) {
            typeValid = $('#appliance_type_manual').val().trim() !== '';
        } else {
            typeValid = $('#appliance_type_select').val() !== '';
        }
        
        const dateValid = $('#preferred_date').val() !== '';
        
        const fullNameValid = $('input[name="full_name"]').val().trim() !== '';
        const phoneValid = $('input[name="phone_number"]').val().trim() !== '';
        const emailValue = $('input[name="customer_email"]').val().trim();
        const emailValid = emailValue !== '' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailValue);
        const addressValid = $('textarea[name="service_address"]').val().trim() !== '';
        const modelValid = $('input[name="model_number"]').val().trim() !== '';
        const serialValid = $('input[name="serial_number"]').val().trim() !== '';
        const issueValid = $('textarea[name="issue_description"]').val().trim() !== '';
        const warrantyValid = $('select[name="warranty_type"]').val() !== '';
        
        if(zipValid && brandValid && typeValid && dateValid && 
           fullNameValid && phoneValid && emailValid && addressValid && modelValid && serialValid && issueValid && warrantyValid) {
            $('#submitBtn').prop('disabled', false);
        } else {
            $('#submitBtn').prop('disabled', true);
        }
    }
    
    function showToast(message, type) {
        let toast = new bootstrap.Toast(document.getElementById('liveToast'));
        let toastElement = $('#liveToast');
        
        toastElement.removeClass('bg-success bg-danger');
        if(type === 'success') {
            toastElement.addClass('bg-success');
            $('#toastTitle').text('Success');
        } else {
            toastElement.addClass('bg-danger');
            $('#toastTitle').text('Error');
        }
        
        $('#toastMessage').text(message);
        toast.show();
    }
    </script>
</body>
</html>