<?php
// team_leader/manual_ticket.php - Manual ticket entry for Team Leaders
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

$currentCsrId = (int)$_SESSION['csr_id'];
$title = 'Manual Ticket';

ob_start();
require_once '../config/database.php';
require_once '../includes/app_helpers.php';

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

$ticketCsrName = 'CSR';
try {
    $csrStmt = $db->prepare("SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM csr_users WHERE id = :id LIMIT 1");
    $csrStmt->execute([':id' => $currentCsrId]);
    $ticketCsrName = trim((string)$csrStmt->fetchColumn()) ?: 'CSR';
} catch (Exception $e) {
    $ticketCsrName = 'CSR';
}

function ensureCsrManualTicketColumns(PDO $db): void {
    addColumnIfMissing($db, 'service_requests', 'ticket_source', "VARCHAR(80) NULL AFTER request_number");
    addColumnIfMissing($db, 'service_requests', 'manual_ticket_number', "VARCHAR(80) NULL AFTER ticket_source");
    addColumnIfMissing($db, 'service_requests', 'secondary_phone', "VARCHAR(30) NULL AFTER phone_number");
    addColumnIfMissing($db, 'service_requests', 'customer_email', "VARCHAR(150) NULL AFTER secondary_phone");
    addColumnIfMissing($db, 'service_requests', 'product_model_version', "VARCHAR(120) NULL AFTER serial_number");
    addColumnIfMissing($db, 'service_requests', 'purchase_date', "DATE NULL AFTER special_request");
    addColumnIfMissing($db, 'service_requests', 'warranty_type', "VARCHAR(80) NULL AFTER purchase_date");
    addColumnIfMissing($db, 'service_requests', 'call_received_date', "DATE NULL AFTER warranty_type");
    addColumnIfMissing($db, 'service_requests', 'is_fake_ticket', "TINYINT(1) NOT NULL DEFAULT 0 AFTER call_received_date");
    addColumnIfMissing($db, 'service_requests', 'created_by_csr_id', "INT NULL AFTER is_fake_ticket");

    // Manual call/ticket numbers can be longer than the original SRV auto-number.
    try {
        $stmt = $db->prepare("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'service_requests' AND COLUMN_NAME = 'request_number' LIMIT 1");
        $stmt->execute();
        $currentLength = (int)$stmt->fetchColumn();
        if ($currentLength > 0 && $currentLength < 80) {
            $db->exec("ALTER TABLE service_requests MODIFY request_number VARCHAR(80) NOT NULL");
        }
    } catch (Exception $e) {
        // Do not block the page if the DB user cannot alter column length.
    }
}

function cleanValue(string $key, $default = null) {
    return isset($_POST[$key]) ? trim((string)$_POST[$key]) : $default;
}

function dateOrNull($value) {
    $value = trim((string)$value);
    if ($value === '') return null;
    $ts = strtotime($value);
    return $ts ? date('Y-m-d', $ts) : null;
}

function makeUniqueRequestNumber(PDO $db, string $requestedTicketNo = ''): string {
    $requestedTicketNo = trim($requestedTicketNo);
    if ($requestedTicketNo !== '' && mb_strlen($requestedTicketNo) > 80) {
        $requestedTicketNo = mb_substr($requestedTicketNo, 0, 80);
    }
    if ($requestedTicketNo !== '') {
        $stmt = $db->prepare("SELECT COUNT(*) FROM service_requests WHERE request_number = :request_number");
        $stmt->execute([':request_number' => $requestedTicketNo]);
        if ((int)$stmt->fetchColumn() === 0) {
            return $requestedTicketNo;
        }
    }

    do {
        $requestNumber = 'CALL-' . date('Ymd') . '-' . random_int(1000, 9999);
        $stmt = $db->prepare("SELECT COUNT(*) FROM service_requests WHERE request_number = :request_number");
        $stmt->execute([':request_number' => $requestNumber]);
    } while ((int)$stmt->fetchColumn() > 0);

    return $requestNumber;
}

ensureCsrManualTicketColumns($db);
ensureAddressAndCallQueueTables($db);
ensureUnifiedTicketWorkflow($db);

$successMessage = '';
$errorMessage = '';
$newRequestNumber = '';

$states = ['AL','AR','FL','GA','IL','IN','KY','LA','MS','MO','NC','OK','SC','TN','TX','VA'];
$sources = ['Phone Call','Grasshopper','Website','Email','Referral','Follow-up','Other'];
$warrantyTypes = ['Manufacturer Warranty','Extended Warranty','Home Warranty','Out of Warranty','Unknown'];

$brands = $db->query("SELECT id, name FROM brands ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$applianceTypes = $db->query("SELECT id, name FROM appliance_types ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$urgencyLevels = $db->query("SELECT id, name FROM urgency_levels ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $required = [
            'source' => 'Source',
            'full_name' => 'Name',
            'service_address' => 'Address',
            'region' => 'Region',
            'city' => 'City',
            'zip_code' => 'Zip Code',
            'state' => 'State',
            'model_number' => 'Model',
            'serial_number' => 'Serial',
            'brand' => 'Brand',
            'product_category' => 'Product Category',
            'warranty_type' => 'Warranty Type',
            'call_received_date' => 'Call Received Date',
            'issue_description' => 'Problem Description'
        ];

        foreach ($required as $key => $label) {
            if (cleanValue($key, '') === '') {
                throw new Exception($label . ' is required.');
            }
        }

        $source = cleanValue('source', 'Phone Call');
        $fullName = cleanValue('full_name', '');
        $primaryPhone = cleanValue('primary_phone', '');
        $secondaryPhone = cleanValue('secondary_phone', '');
        $email = cleanValue('email', '');
        $address = cleanValue('service_address', '');
        $region = cleanValue('region', '');
        $cityName = cleanValue('city', '');
        $state = strtoupper(cleanValue('state', ''));
        $zipCode = cleanValue('zip_code', '');
        $zipMeta = getZipAddressMeta($db, $zipCode);
        if ($zipMeta) {
            $region = $region ?: ($zipMeta['region'] ?? '');
            $cityName = $cityName ?: ($zipMeta['city_name'] ?? '');
            $state = $state ?: strtoupper($zipMeta['state'] ?? '');
        }
        $addressNote = cleanValue('address_note', '');
        $modelNumber = cleanValue('model_number', '');
        $serialNumber = cleanValue('serial_number', '');
        $modelVersion = cleanValue('product_model_version', '');
        $brandName = cleanValue('brand', '');
        $productCategory = cleanValue('product_category', '');
        $warrantyType = cleanValue('warranty_type', '');
        $purchaseDate = dateOrNull(cleanValue('purchase_date', ''));
        $preferredDate = dateOrNull(cleanValue('preferred_date', ''));
        $callReceivedDate = dateOrNull(cleanValue('call_received_date', ''));
        $issueDescription = cleanValue('issue_description', '');
        $isFakeTicket = isset($_POST['is_fake_ticket']) ? 1 : 0;
        $urgencyLevelId = (int)(cleanValue('urgency_level_id', '1') ?: 1);

        if ($primaryPhone === '' && $secondaryPhone === '' && $email === '') {
            throw new Exception('Please enter at least one contact detail: primary phone, secondary phone, or email.');
        }

        if ($callReceivedDate === null) {
            throw new Exception('Call Received Date is invalid.');
        }

        // Create lock/ownership table BEFORE the transaction.
        // MySQL/MariaDB DDL causes an implicit commit, so doing CREATE TABLE inside
        // a transaction can trigger: "There is no active transaction".
        try {
            $db->exec("CREATE TABLE IF NOT EXISTS csr_request_locks (
                id INT AUTO_INCREMENT PRIMARY KEY,
                request_id INT NOT NULL UNIQUE,
                csr_id INT NOT NULL,
                csr_name VARCHAR(255) NOT NULL,
                locked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        } catch (Exception $lockTableError) {
            // Do not block ticket creation if hosting permissions restrict CREATE TABLE.
        }

        $db->beginTransaction();

        $cityId = $zipMeta['city_id'] ?? null;
        if (!$cityId) {
            $cityStmt = $db->prepare("SELECT id FROM cities WHERE LOWER(city_name) = LOWER(:city_name) AND LOWER(state) = LOWER(:state) LIMIT 1");
            $cityStmt->execute([':city_name' => $cityName, ':state' => $state]);
            $cityId = $cityStmt->fetchColumn();
        }
        if (!$cityId) {
            $insertCity = $db->prepare("INSERT INTO cities (city_name, region, state, is_active) VALUES (:city_name, :region, :state, 1)");
            $insertCity->execute([':city_name' => $cityName, ':region' => $region, ':state' => $state]);
            $cityId = $db->lastInsertId();
        }

        $brandId = null;
        $brandStmt = $db->prepare("SELECT id FROM brands WHERE LOWER(name) = LOWER(:name) LIMIT 1");
        $brandStmt->execute([':name' => $brandName]);
        $brandId = $brandStmt->fetchColumn() ?: null;

        $applianceTypeId = null;
        $applianceStmt = $db->prepare("SELECT id FROM appliance_types WHERE LOWER(name) = LOWER(:name) LIMIT 1");
        $applianceStmt->execute([':name' => $productCategory]);
        $applianceTypeId = $applianceStmt->fetchColumn() ?: null;

        $requestNumber = makeUniqueRequestNumber($db, cleanValue('ticket_no', ''));

        $details = [];
        if ($source !== '') $details[] = "Source: " . $source;
        if ($email !== '') $details[] = "Email: " . $email;
        if ($secondaryPhone !== '') $details[] = "Secondary Phone: " . $secondaryPhone;
        if ($state !== '') $details[] = "State: " . $state;
        if ($addressNote !== '') $details[] = "Address Note: " . $addressNote;
        if ($modelVersion !== '') $details[] = "Model Version: " . $modelVersion;
        if ($purchaseDate !== null) $details[] = "Purchase Date: " . $purchaseDate;
        if ($warrantyType !== '') $details[] = "Warranty Type: " . $warrantyType;
        if ($callReceivedDate !== null) $details[] = "Call Received Date: " . $callReceivedDate;
        if ($isFakeTicket) $details[] = "Fake Ticket: Yes - not included statistically.";

        $specialRequest = implode("\n", $details);

        $insert = $db->prepare("INSERT INTO service_requests (
            customer_id, request_number, ticket_source, manual_ticket_number, brand_id, manual_brand, appliance_type_id, manual_appliance_type,
            model_number, serial_number, product_model_version, full_name, phone_number, secondary_phone, customer_email,
            service_address, service_address_2, region, city_id, state, zip_code, landmark, urgency_level_id, job_status_id,
            issue_description, special_request, purchase_date, warranty_type, call_received_date, is_fake_ticket,
            preferred_date, preferred_time, location_id, is_serviceable, created_by_csr_id, last_updated_at
        ) VALUES (
            NULL, :request_number, :ticket_source, :manual_ticket_number, :brand_id, :manual_brand, :appliance_type_id, :manual_appliance_type,
            :model_number, :serial_number, :product_model_version, :full_name, :phone_number, :secondary_phone, :customer_email,
            :service_address, :service_address_2, :region, :city_id, :state, :zip_code, :landmark, :urgency_level_id, 1,
            :issue_description, :special_request, :purchase_date, :warranty_type, :call_received_date, :is_fake_ticket,
            :preferred_date, '00:00:00', :location_id, 1, :created_by_csr_id, NOW()
        )");

        $insert->execute([
            ':request_number' => $requestNumber,
            ':ticket_source' => 'csr_manual',
            ':manual_ticket_number' => $requestNumber,
            ':brand_id' => $brandId,
            ':manual_brand' => $brandId ? '' : $brandName,
            ':appliance_type_id' => $applianceTypeId,
            ':manual_appliance_type' => $applianceTypeId ? '' : $productCategory,
            ':model_number' => $modelNumber,
            ':serial_number' => $serialNumber,
            ':product_model_version' => $modelVersion,
            ':full_name' => $fullName,
            ':phone_number' => $primaryPhone ?: $secondaryPhone,
            ':secondary_phone' => $secondaryPhone,
            ':customer_email' => $email,
            ':service_address' => $address,
            ':service_address_2' => $addressNote,
            ':region' => $region,
            ':city_id' => $cityId,
            ':state' => $state,
            ':zip_code' => $zipCode,
            ':landmark' => $addressNote,
            ':urgency_level_id' => $urgencyLevelId,
            ':issue_description' => $issueDescription,
            ':special_request' => $specialRequest,
            ':purchase_date' => $purchaseDate,
            ':warranty_type' => $warrantyType,
            ':call_received_date' => $callReceivedDate,
            ':is_fake_ticket' => $isFakeTicket,
            ':preferred_date' => $preferredDate,
            ':location_id' => $zipMeta['location_id'] ?? null,
            ':created_by_csr_id' => $currentCsrId,
        ]);

        $requestId = (int)$db->lastInsertId();

        // Immediately lock/own the manual ticket to the CSR who created it.
        // This makes it appear in Manual Request even before a technician/chat assignment exists.
        try {
            $lockStmt = $db->prepare("INSERT INTO csr_request_locks (request_id, csr_id, csr_name)
                                      VALUES (:request_id, :csr_id, :csr_name)
                                      ON DUPLICATE KEY UPDATE csr_id = VALUES(csr_id), csr_name = VALUES(csr_name)");
            $lockStmt->execute([
                ':request_id' => $requestId,
                ':csr_id' => $currentCsrId,
                ':csr_name' => $ticketCsrName
            ]);
        } catch (Exception $lockError) {
            // Do not block ticket creation if lock table creation is restricted by hosting permissions.
        }

        $db->commit();

        // History/activity logging should never prevent the ticket itself from being created.
        try {
            $history = $db->prepare("INSERT INTO request_status_history (request_id, job_status_id, notes, changed_by) VALUES (:request_id, 1, :notes, :changed_by)");
            $history->execute([
                ':request_id' => $requestId,
                ':notes' => 'Manual ticket created by CSR from call entry.',
                ':changed_by' => $ticketCsrName
            ]);
        } catch (Exception $logError) {}

        try {
            logRequestAction($db, $requestId, $currentCsrId, 'csr', 'manual_ticket_created', null, $requestNumber, $specialRequest);
            logCSRActivity($db, $currentCsrId, 'manual_ticket_created', $requestId, 'CSR manually created ticket #' . $requestNumber);
        } catch (Exception $logError) {}

        $successMessage = 'Ticket created successfully. Ticket No: ' . h($requestNumber);
        $newRequestNumber = $requestNumber;
        $_POST = [];
    } catch (Exception $e) {
        if (isset($db) && $db->inTransaction()) {
            $db->rollBack();
        }
        $errorMessage = $e->getMessage();
    }
}

$today = date('Y-m-d');
?>

<style>
.ticket-page-wrap { max-width: 1180px; margin: 0 auto; }
.ticket-hero { display:flex; justify-content:space-between; gap:18px; align-items:center; margin-bottom:18px; }
.ticket-hero h2 { margin:0; font-weight:800; color:#fff; }
.ticket-hero p { margin:6px 0 0; color:var(--ushs-muted); }
.ticket-section { background:linear-gradient(180deg, rgba(27,45,91,.82), rgba(20,39,72,.78)); border:1px solid rgba(80,198,244,.22); border-radius:16px; padding:22px; margin-bottom:22px; box-shadow:0 18px 50px rgba(0,0,0,.25); }
.ticket-section-title { color:var(--ushs-cyan); font-weight:800; font-size:18px; padding-bottom:12px; margin-bottom:18px; border-bottom:1px solid rgba(143,190,231,.18); }
.ticket-required { color:#ff7777; }
.ticket-actions { display:flex; gap:12px; justify-content:flex-end; align-items:center; flex-wrap:wrap; }
.ticket-submit { border:0; border-radius:12px; padding:12px 22px; font-weight:800; color:#fff; background:linear-gradient(135deg,#1677ff,#4fc3f7); box-shadow:0 12px 28px rgba(22,119,255,.25); }
.ticket-reset { border:1px solid rgba(143,190,231,.24); border-radius:12px; padding:12px 22px; color:#fff; background:rgba(255,255,255,.07); text-decoration:none; }
.form-check-input { width:18px; height:18px; margin-top:.2rem; }
.alert.ticket-alert { border-radius:14px; border:1px solid rgba(255,255,255,.16); }
.quick-note { color:#ffffff !important; font-size:13px; }
.ticket-page-wrap,
.ticket-page-wrap p,
.ticket-page-wrap span,
.ticket-page-wrap div,
.ticket-page-wrap label,
.ticket-page-wrap .form-label,
.ticket-page-wrap .form-check-label,
.ticket-page-wrap .quick-note,
.ticket-page-wrap .ticket-section-title {
    color:#ffffff !important;
}
.ticket-page-wrap input,
.ticket-page-wrap textarea,
.ticket-page-wrap select {
    color:#ffffff !important;
    background-color:rgba(7,18,44,.82) !important;
    border-color:rgba(143,190,231,.34) !important;
}
.ticket-page-wrap input::placeholder,
.ticket-page-wrap textarea::placeholder {
    color:rgba(255,255,255,.68) !important;
}
.ticket-page-wrap select option,
.ticket-page-wrap datalist option {
    color:#ffffff !important;
    background:#102448 !important;
}
.ticket-page-wrap .alert-success,
.ticket-page-wrap .alert-danger { color:#ffffff !important; }
</style>

<div class="ticket-page-wrap">
    <div class="ticket-hero">
        <div>
            <h2><i class="fas fa-ticket-alt me-2 text-primary"></i> Manual Ticket Entry</h2>
            <p>For CSR phone calls. Enter the customer and product details, then submit the ticket into the request queue.</p>
        </div>
        <?php if ($newRequestNumber): ?>
            <?php
            $returnUrl = $_SESSION['ticket_return_url'] ?? 'requests.php';
            unset($_SESSION['ticket_return_url']);
            ?>
            <a class="ticket-reset" href="<?= htmlspecialchars($returnUrl, ENT_QUOTES, 'UTF-8') ?>"><i class="fas fa-list me-2"></i>View All Requests</a>
        <?php endif; ?>
    </div>

    <?php if ($successMessage): ?>
        <div class="alert alert-success ticket-alert"><i class="fas fa-check-circle me-2"></i><?php echo $successMessage; ?></div>
    <?php endif; ?>
    <?php if ($errorMessage): ?>
        <div class="alert alert-danger ticket-alert"><i class="fas fa-exclamation-triangle me-2"></i><?php echo h($errorMessage); ?></div>
    <?php endif; ?>

    <form method="POST" autocomplete="off">
        <div class="ticket-section">
            <div class="ticket-section-title">Customer Information</div>
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label">Ticket No <span class="ticket-required">*</span></label>
                    <input type="text" name="ticket_no" class="form-control" value="<?php echo h($_POST['ticket_no'] ?? ''); ?>" placeholder="Auto if blank">
                </div>
                <div class="col-md-4">
                    <div class="form-check mt-4">
                        <input class="form-check-input" type="checkbox" name="is_fake_ticket" id="is_fake_ticket" <?php echo isset($_POST['is_fake_ticket']) ? 'checked' : ''; ?>>
                        <label class="form-check-label fw-bold" for="is_fake_ticket">Fake Ticket (not included statistically)</label>
                    </div>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Source <span class="ticket-required">*</span></label>
                    <select name="source" class="form-select" required>
                        <option value="">Select Source</option>
                        <?php foreach ($sources as $sourceOption): ?>
                            <option value="<?php echo h($sourceOption); ?>" <?php echo (($_POST['source'] ?? 'Phone Call') === $sourceOption) ? 'selected' : ''; ?>><?php echo h($sourceOption); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Name <span class="ticket-required">*</span></label>
                    <input type="text" name="full_name" class="form-control" required value="<?php echo h($_POST['full_name'] ?? ''); ?>">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Primary Phone</label>
                    <input type="text" name="primary_phone" class="form-control" value="<?php echo h($_POST['primary_phone'] ?? ''); ?>">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Secondary Phone</label>
                    <input type="text" name="secondary_phone" class="form-control" value="<?php echo h($_POST['secondary_phone'] ?? ''); ?>">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-control" value="<?php echo h($_POST['email'] ?? ''); ?>">
                </div>
                <div class="col-12">
                    <label class="form-label">Address <span class="ticket-required">*</span></label>
                    <input type="text" name="service_address" class="form-control" required value="<?php echo h($_POST['service_address'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Region <span class="ticket-required">*</span></label>
                    <input type="text" name="region" id="ticket_region" class="form-control" required value="<?php echo h($_POST['region'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">City <span class="ticket-required">*</span></label>
                    <input type="text" name="city" id="ticket_city" class="form-control" required value="<?php echo h($_POST['city'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Zip Code <span class="ticket-required">*</span></label>
                    <input type="text" name="zip_code" id="ticket_zip" class="form-control" required value="<?php echo h($_POST['zip_code'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">State <span class="ticket-required">*</span></label>
                    <select name="state" id="ticket_state" class="form-select" required>
                        <option value="">Select State</option>
                        <?php foreach ($states as $stateOption): ?>
                            <option value="<?php echo h($stateOption); ?>" <?php echo (($_POST['state'] ?? '') === $stateOption) ? 'selected' : ''; ?>><?php echo h($stateOption); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Address Note</label>
                    <textarea name="address_note" rows="4" class="form-control"><?php echo h($_POST['address_note'] ?? ''); ?></textarea>
                </div>
            </div>
        </div>

        <div class="ticket-section">
            <div class="ticket-section-title">Product Information</div>
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">Model <span class="ticket-required">*</span></label>
                    <input type="text" name="model_number" class="form-control" required value="<?php echo h($_POST['model_number'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Serial <span class="ticket-required">*</span></label>
                    <input type="text" name="serial_number" class="form-control" required value="<?php echo h($_POST['serial_number'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Model Version</label>
                    <input type="text" name="product_model_version" class="form-control" value="<?php echo h($_POST['product_model_version'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Brand <span class="ticket-required">*</span></label>
                    <input class="form-control" name="brand" list="brandOptions" required value="<?php echo h($_POST['brand'] ?? ''); ?>">
                    <datalist id="brandOptions">
                        <?php foreach ($brands as $brand): ?><option value="<?php echo h($brand['name']); ?>"></option><?php endforeach; ?>
                    </datalist>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Product Category <span class="ticket-required">*</span></label>
                    <input class="form-control" name="product_category" list="categoryOptions" required value="<?php echo h($_POST['product_category'] ?? ''); ?>">
                    <datalist id="categoryOptions">
                        <?php foreach ($applianceTypes as $type): ?><option value="<?php echo h($type['name']); ?>"></option><?php endforeach; ?>
                    </datalist>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Urgency</label>
                    <select name="urgency_level_id" class="form-select">
                        <?php foreach ($urgencyLevels as $urgency): ?>
                            <option value="<?php echo (int)$urgency['id']; ?>" <?php echo (($_POST['urgency_level_id'] ?? '1') == $urgency['id']) ? 'selected' : ''; ?>><?php echo h($urgency['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Purchase Date</label>
                    <input type="date" name="purchase_date" class="form-control" value="<?php echo h($_POST['purchase_date'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Warranty Type <span class="ticket-required">*</span></label>
                    <select name="warranty_type" class="form-select" required>
                        <option value="">Select Warranty Type</option>
                        <?php foreach ($warrantyTypes as $warranty): ?>
                            <option value="<?php echo h($warranty); ?>" <?php echo (($_POST['warranty_type'] ?? '') === $warranty) ? 'selected' : ''; ?>><?php echo h($warranty); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Cx Preferred Date</label>
                    <input type="date" name="preferred_date" class="form-control" value="<?php echo h($_POST['preferred_date'] ?? ''); ?>">
                </div>
            </div>
        </div>

        <div class="ticket-section">
            <div class="ticket-section-title">Call (Service) Information</div>
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">Call Received Date <span class="ticket-required">*</span></label>
                    <input type="date" name="call_received_date" class="form-control" required value="<?php echo h($_POST['call_received_date'] ?? $today); ?>">
                </div>
                <div class="col-12">
                    <label class="form-label">Problem Description <span class="ticket-required">*</span></label>
                    <textarea name="issue_description" rows="6" class="form-control" required><?php echo h($_POST['issue_description'] ?? ''); ?></textarea>
                </div>
            </div>
        </div>

        <div class="ticket-actions mb-4">
            <span class="quick-note me-auto">Submitted tickets will appear in CSR/Admin request lists with status New Request.</span>
            <a href="manual_ticket.php" class="ticket-reset"><i class="fas fa-rotate-left me-2"></i>Reset</a>
            <button type="submit" class="ticket-submit"><i class="fas fa-save me-2"></i>Create Ticket</button>
        </div>
    </form>
</div>


<script>
(function(){
    const zip = document.getElementById('ticket_zip');
    if (!zip) return;
    let timer = null;
    zip.addEventListener('input', function(){
        clearTimeout(timer);
        const value = this.value.trim();
        if (value.length !== 5) return;
        timer = setTimeout(function(){
            fetch('../customer/check_zip.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'zip_code=' + encodeURIComponent(value)
            }).then(r => r.json()).then(data => {
                if (!data || !data.serviceable) return;
                if (data.region) document.getElementById('ticket_region').value = data.region;
                if (data.city_name) document.getElementById('ticket_city').value = data.city_name;
                if (data.state) document.getElementById('ticket_state').value = data.state;
            }).catch(()=>{});
        }, 300);
    });
})();
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>
