<?php
// admin/extras.php - Versioni për Worker (View Only)
require_once '../includes/config.php';

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

$user_role = $_SESSION['admin_role'] ?? 'admin';
$is_worker = ($user_role == 'worker');

$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'insurance';
$message = '';
$error = '';

// ============================================
// INSURANCE CRUD - VETËM ADMIN
// ============================================
if(isset($_POST['add_insurance']) && !$is_worker) {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $price_per_day = !empty($_POST['price_per_day']) ? (float)$_POST['price_per_day'] : null;
    $price_one_time = !empty($_POST['price_one_time']) ? (float)$_POST['price_one_time'] : null;
    $is_daily = isset($_POST['is_daily']) ? 1 : 0;
    $sort_order = (int)$_POST['sort_order'];
    
    $stmt = $pdo->prepare("INSERT INTO insurance_types (name, description, price_per_day, price_one_time, is_daily, sort_order) VALUES (?, ?, ?, ?, ?, ?)");
    if($stmt->execute([$name, $description, $price_per_day, $price_one_time, $is_daily, $sort_order])) {
        $message = "Insurance type added successfully!";
    } else {
        $error = "Failed to add insurance type.";
    }
}

if(isset($_POST['update_insurance']) && !$is_worker) {
    $id = (int)$_POST['id'];
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $price_per_day = !empty($_POST['price_per_day']) ? (float)$_POST['price_per_day'] : null;
    $price_one_time = !empty($_POST['price_one_time']) ? (float)$_POST['price_one_time'] : null;
    $is_daily = isset($_POST['is_daily']) ? 1 : 0;
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $sort_order = (int)$_POST['sort_order'];
    
    $stmt = $pdo->prepare("UPDATE insurance_types SET name = ?, description = ?, price_per_day = ?, price_one_time = ?, is_daily = ?, is_active = ?, sort_order = ? WHERE id = ?");
    if($stmt->execute([$name, $description, $price_per_day, $price_one_time, $is_daily, $is_active, $sort_order, $id])) {
        $message = "Insurance type updated successfully!";
    } else {
        $error = "Failed to update insurance type.";
    }
}

if(isset($_GET['delete_insurance']) && !$is_worker) {
    $id = (int)$_GET['delete_insurance'];
    $stmt = $pdo->prepare("DELETE FROM insurance_types WHERE id = ? AND price_per_day > 0");
    if($stmt->execute([$id])) {
        $message = "Insurance type deleted successfully!";
    } else {
        $error = "Cannot delete - may have associated reservations or is default insurance.";
    }
}

// ============================================
// ADDITIONAL OPTIONS CRUD - VETËM ADMIN
// ============================================
if(isset($_POST['add_option']) && !$is_worker) {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $icon = trim($_POST['icon']);
    $price_per_day = !empty($_POST['price_per_day']) ? (float)$_POST['price_per_day'] : null;
    $price_one_time = !empty($_POST['price_one_time']) ? (float)$_POST['price_one_time'] : null;
    $is_daily = isset($_POST['is_daily']) ? 1 : 0;
    $max_quantity = (int)$_POST['max_quantity'];
    if($max_quantity < 1) $max_quantity = 1;
    $sort_order = (int)$_POST['sort_order'];
    
    $stmt = $pdo->prepare("INSERT INTO additional_options (name, description, icon, price_per_day, price_one_time, is_daily, max_quantity, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    if($stmt->execute([$name, $description, $icon, $price_per_day, $price_one_time, $is_daily, $max_quantity, $sort_order])) {
        $message = "Additional option added successfully!";
    } else {
        $error = "Failed to add option.";
    }
}

if(isset($_POST['update_option']) && !$is_worker) {
    $id = (int)$_POST['id'];
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $icon = trim($_POST['icon']);
    $price_per_day = !empty($_POST['price_per_day']) ? (float)$_POST['price_per_day'] : null;
    $price_one_time = !empty($_POST['price_one_time']) ? (float)$_POST['price_one_time'] : null;
    $is_daily = isset($_POST['is_daily']) ? 1 : 0;
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $max_quantity = (int)$_POST['max_quantity'];
    if($max_quantity < 1) $max_quantity = 1;
    $sort_order = (int)$_POST['sort_order'];
    
    $stmt = $pdo->prepare("UPDATE additional_options SET name = ?, description = ?, icon = ?, price_per_day = ?, price_one_time = ?, is_daily = ?, is_active = ?, max_quantity = ?, sort_order = ? WHERE id = ?");
    if($stmt->execute([$name, $description, $icon, $price_per_day, $price_one_time, $is_daily, $is_active, $max_quantity, $sort_order, $id])) {
        $message = "Option updated successfully!";
    } else {
        $error = "Failed to update option.";
    }
}

if(isset($_GET['delete_option']) && !$is_worker) {
    $id = (int)$_GET['delete_option'];
    $stmt = $pdo->prepare("DELETE FROM additional_options WHERE id = ?");
    if($stmt->execute([$id])) {
        $message = "Option deleted successfully!";
    } else {
        $error = "Failed to delete option.";
    }
}

// Get data
$insurance_types = $pdo->query("SELECT * FROM insurance_types ORDER BY sort_order, id")->fetchAll();
$additional_options = $pdo->query("SELECT * FROM additional_options ORDER BY sort_order, id")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Extras Management - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        
        .sidebar {
            width: 260px;
            background: #1a1a2e;
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
        }
        .sidebar-header { padding: 24px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header h2 { font-size: 18px; font-weight: 600; }
        .sidebar-nav { padding: 20px 0; }
        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: #cbd5e1;
            text-decoration: none;
            font-size: 14px;
        }
        .sidebar-nav a i { width: 20px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: #0066cc; color: white; }
        .sidebar-nav a.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
        }
        
        .main-content { margin-left: 260px; padding: 24px; }
        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 24px; font-weight: 600; }
        
        .worker-badge {
            display: inline-block;
            background: #fef3c7;
            color: #92400e;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .tabs {
            display: flex;
            gap: 4px;
            margin-bottom: 24px;
            background: white;
            border-radius: 12px;
            padding: 4px;
            border: 1px solid #e5e7eb;
        }
        .tab {
            flex: 1;
            padding: 12px 20px;
            text-align: center;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.2s;
            font-weight: 500;
        }
        .tab.active {
            background: #0066cc;
            color: white;
        }
        
        .card {
            background: white;
            border-radius: 16px;
            border: 1px solid #e5e7eb;
            margin-bottom: 24px;
            overflow: hidden;
        }
        .card-header {
            padding: 16px 20px;
            background: #f9fafb;
            border-bottom: 1px solid #e5e7eb;
            font-weight: 600;
            font-size: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
        }
        .card-header button {
            background: #0066cc;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 13px;
        }
        .card-header button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .card-header .view-only-badge {
            font-size: 12px;
            color: #6b7280;
            font-weight: 400;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        .data-table th, .data-table td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
            font-size: 13px;
        }
        .data-table th {
            background: #f9fafb;
            font-weight: 600;
        }
        .data-table tr:hover {
            background: #f9fafb;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        .status-active { background: #d1fae5; color: #065f46; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        
        .btn-icon {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            margin: 0 2px;
        }
        .btn-edit { background: #e0e7ff; color: #3730a3; }
        .btn-delete { background: #fee2e2; color: #991b1b; }
        .btn-icon:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .btn-lock {
            color: #94a3b8;
            font-size: 12px;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .modal-content {
            background: white;
            border-radius: 16px;
            width: 500px;
            max-width: 95%;
            max-height: 90vh;
            overflow-y: auto;
        }
        .modal-header {
            padding: 16px 20px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .modal-body { padding: 20px; }
        .modal-footer {
            padding: 16px 20px;
            border-top: 1px solid #e5e7eb;
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }
        
        .form-group { margin-bottom: 16px; }
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            font-size: 13px;
            color: #374151;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 14px;
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .checkbox-group input {
            width: auto;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .alert-info {
            background: #eff6ff;
            color: #1e40af;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #3b82f6;
        }
        
        .btn-primary {
            background: #0066cc;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }
        .btn-secondary {
            background: #6b7280;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }
        
        .help-text {
            font-size: 11px;
            color: #6b7280;
            margin-top: 4px;
            display: block;
        }
        
        @media (max-width: 768px) {
            .sidebar { width: 100%; position: relative; height: auto; }
            .main-content { margin-left: 0; }
            .data-table { display: block; overflow-x: auto; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header"><h2><i class="fas fa-car"></i> Car Rental Admin</h2></div>
        <div class="sidebar-nav">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="cars.php"><i class="fas fa-car"></i> Cars</a>
            <a href="create-reservation.php"><i class="fas fa-plus-square"></i> Create Reservation</a>
            <a href="reservations.php"><i class="fas fa-calendar-check"></i> Reservations</a>
            <a href="calendar.php"><i class="fas fa-calendar-alt"></i> Calendar</a>
            <a href="price-list.php"><i class="fas fa-tags"></i> Price Rules</a>
            <a href="extras.php" class="active"><i class="fas fa-cogs"></i> Extras</a>
            <a href="email-settings.php"><i class="fas fa-envelope"></i> Email Settings</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="manage-admins.php"><i class="fas fa-user-shield"></i> Users</a>
            <a href="clients.php"><i class="fas fa-users"></i> Clients</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <div class="page-header">
            <h1>
                <i class="fas fa-cogs"></i> Extras Management
                <?php if($is_worker): ?>
                    <span class="worker-badge"><i class="fas fa-eye"></i> View Only</span>
                <?php endif; ?>
            </h1>
        </div>
        
        <?php if($message): ?>
            <div class="alert-success"><?php echo $message; ?></div>
        <?php endif; ?>
        <?php if($error): ?>
            <div class="alert-error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if($is_worker): ?>
            <div class="alert-info">
                <i class="fas fa-info-circle"></i> 
                <strong>View Only Mode:</strong> You can view insurance types and additional options but cannot add, edit, or delete them. Contact an administrator to make changes.
            </div>
        <?php endif; ?>
        
        <div class="tabs">
            <div class="tab <?php echo $active_tab == 'insurance' ? 'active' : ''; ?>" onclick="switchTab('insurance')">
                <i class="fas fa-shield-alt"></i> Insurance Types
            </div>
            <div class="tab <?php echo $active_tab == 'options' ? 'active' : ''; ?>" onclick="switchTab('options')">
                <i class="fas fa-plus-circle"></i> Additional Options
            </div>
        </div>
        
        <!-- Insurance Types Section -->
        <div id="insuranceSection" style="display: <?php echo $active_tab == 'insurance' ? 'block' : 'none'; ?>">
            <div class="card">
                <div class="card-header">
                    <span><i class="fas fa-shield-alt"></i> Insurance Types</span>
                    <?php if(!$is_worker): ?>
                        <button onclick="openInsuranceModal()"><i class="fas fa-plus"></i> Add Insurance</button>
                    <?php else: ?>
                        <span class="view-only-badge"><i class="fas fa-lock"></i> View Only</span>
                    <?php endif; ?>
                </div>
                <table class="data-table">
                    <thead>
                        <tr><th>Name</th><th>Description</th><th>Price/Day</th><th>One-time</th><th>Status</th><th>Order</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach($insurance_types as $ins): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($ins['name']); ?></strong></td>
                            <td><?php echo htmlspecialchars(substr($ins['description'], 0, 50)); ?></td>
                            <td><?php echo $ins['price_per_day'] !== null && $ins['price_per_day'] > 0 ? '€' . number_format($ins['price_per_day'], 2) : ($ins['price_per_day'] == 0 ? 'Free' : '-'); ?></td>
                            <td><?php echo $ins['price_one_time'] !== null ? '€' . number_format($ins['price_one_time'], 2) : '-'; ?></td>
                            <td><span class="status-badge <?php echo $ins['is_active'] ? 'status-active' : 'status-inactive'; ?>"><?php echo $ins['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                            <td><?php echo $ins['sort_order']; ?></td>
                            <td>
                                <?php if(!$is_worker): ?>
                                    <button class="btn-icon btn-edit" onclick="editInsurance(<?php echo htmlspecialchars(json_encode($ins)); ?>)"><i class="fas fa-edit"></i> Edit</button>
                                    <?php if($ins['price_per_day'] > 0): ?>
                                    <button class="btn-icon btn-delete" onclick="deleteInsurance(<?php echo $ins['id']; ?>)"><i class="fas fa-trash"></i> Delete</button>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="btn-lock"><i class="fas fa-lock"></i> View Only</span>
                                <?php endif; ?>
                             </td>
                         </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Additional Options Section -->
        <div id="optionsSection" style="display: <?php echo $active_tab == 'options' ? 'block' : 'none'; ?>">
            <div class="card">
                <div class="card-header">
                    <span><i class="fas fa-plus-circle"></i> Additional Options</span>
                    <?php if(!$is_worker): ?>
                        <button onclick="openOptionModal()"><i class="fas fa-plus"></i> Add Option</button>
                    <?php else: ?>
                        <span class="view-only-badge"><i class="fas fa-lock"></i> View Only</span>
                    <?php endif; ?>
                </div>
                <table class="data-table">
                    <thead>
                        <tr><th>Icon</th><th>Name</th><th>Description</th><th>Price/Day</th><th>One-time</th><th>Max Qty</th><th>Status</th><th>Order</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach($additional_options as $opt): ?>
                        <tr>
                            <td><i class="fas <?php echo htmlspecialchars($opt['icon'] ?: 'fa-cog'); ?>"></i></td>
                            <td><strong><?php echo htmlspecialchars($opt['name']); ?></strong></td>
                            <td><?php echo htmlspecialchars(substr($opt['description'], 0, 40)); ?></td>
                            <td><?php echo $opt['price_per_day'] !== null && $opt['price_per_day'] > 0 ? '€' . number_format($opt['price_per_day'], 2) : ($opt['price_per_day'] == 0 ? 'Free' : '-'); ?></td>
                            <td><?php echo $opt['price_one_time'] !== null ? '€' . number_format($opt['price_one_time'], 2) : '-'; ?></td>
                            <td><?php echo $opt['max_quantity']; ?></td>
                            <td><span class="status-badge <?php echo $opt['is_active'] ? 'status-active' : 'status-inactive'; ?>"><?php echo $opt['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                            <td><?php echo $opt['sort_order']; ?></td>
                            <td>
                                <?php if(!$is_worker): ?>
                                    <button class="btn-icon btn-edit" onclick="editOption(<?php echo htmlspecialchars(json_encode($opt)); ?>)"><i class="fas fa-edit"></i> Edit</button>
                                    <button class="btn-icon btn-delete" onclick="deleteOption(<?php echo $opt['id']; ?>)"><i class="fas fa-trash"></i> Delete</button>
                                <?php else: ?>
                                    <span class="btn-lock"><i class="fas fa-lock"></i> View Only</span>
                                <?php endif; ?>
                             </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Insurance Modal -->
    <div id="insuranceModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="insuranceModalTitle">Add Insurance Type</h3>
                <span class="close" onclick="closeModal('insuranceModal')">&times;</span>
            </div>
            <form method="POST" id="insuranceForm">
                <div class="modal-body">
                    <input type="hidden" name="id" id="insurance_id">
                    <div class="form-group"><label>Name *</label><input type="text" name="name" id="insurance_name" required></div>
                    <div class="form-group"><label>Description</label><textarea name="description" id="insurance_description" rows="2"></textarea></div>
                    <div class="form-row">
                        <div class="form-group"><label>Price per Day (€)</label><input type="number" step="0.01" name="price_per_day" id="insurance_price_per_day" value="0" placeholder="Leave empty for one-time only"></div>
                        <div class="form-group"><label>One-time Price (€)</label><input type="number" step="0.01" name="price_one_time" id="insurance_price_one_time" placeholder="Leave empty for daily only"></div>
                    </div>
                    <div class="checkbox-group"><input type="checkbox" name="is_daily" id="insurance_is_daily" checked><label>Daily pricing (uncheck for one-time)</label></div>
                    <div class="checkbox-group"><input type="checkbox" name="is_active" id="insurance_is_active" checked><label>Active</label></div>
                    <div class="form-group"><label>Sort Order</label><input type="number" name="sort_order" id="insurance_sort_order" value="0"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-secondary" onclick="closeModal('insuranceModal')">Cancel</button>
                    <button type="submit" name="add_insurance" id="insuranceSubmitBtn" class="btn-primary">Add</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Option Modal -->
    <div id="optionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="optionModalTitle">Add Additional Option</h3>
                <span class="close" onclick="closeModal('optionModal')">&times;</span>
            </div>
            <form method="POST" id="optionForm">
                <div class="modal-body">
                    <input type="hidden" name="id" id="option_id">
                    <div class="form-group"><label>Name *</label><input type="text" name="name" id="option_name" required></div>
                    <div class="form-group"><label>Icon (FontAwesome class, e.g., fa-user-plus)</label><input type="text" name="icon" id="option_icon" placeholder="fa-user-plus"></div>
                    <div class="form-group"><label>Description</label><textarea name="description" id="option_description" rows="2"></textarea></div>
                    <div class="form-row">
                        <div class="form-group"><label>Price per Day (€)</label><input type="number" step="0.01" name="price_per_day" id="option_price_per_day" value="0" placeholder="Leave empty for one-time only"></div>
                        <div class="form-group"><label>One-time Price (€)</label><input type="number" step="0.01" name="price_one_time" id="option_price_one_time" placeholder="Leave empty for daily only"></div>
                    </div>
                    <div class="form-row">
                        <div class="checkbox-group"><input type="checkbox" name="is_daily" id="option_is_daily" checked><label>Daily pricing</label></div>
                        <div class="form-group"><label>Max Quantity</label><input type="number" name="max_quantity" id="option_max_quantity" value="1" min="1" max="10"></div>
                    </div>
                    <div class="help-text">If Max Quantity = 1, a toggle switch will be shown. If >= 2, a quantity dropdown will be shown.</div>
                    <div class="checkbox-group" style="margin-top: 12px;"><input type="checkbox" name="is_active" id="option_is_active" checked><label>Active</label></div>
                    <div class="form-group"><label>Sort Order</label><input type="number" name="sort_order" id="option_sort_order" value="0"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-secondary" onclick="closeModal('optionModal')">Cancel</button>
                    <button type="submit" name="add_option" id="optionSubmitBtn" class="btn-primary">Add</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function switchTab(tab) {
            const url = new URL(window.location.href);
            url.searchParams.set('tab', tab);
            window.location.href = url.toString();
        }
        
        function openInsuranceModal(data = null) {
            <?php if($is_worker): ?>
            alert('Workers cannot add or edit insurance types.');
            return;
            <?php endif; ?>
            
            document.getElementById('insuranceModalTitle').innerText = data ? 'Edit Insurance Type' : 'Add Insurance Type';
            document.getElementById('insurance_id').value = data ? data.id : '';
            document.getElementById('insurance_name').value = data ? data.name : '';
            document.getElementById('insurance_description').value = data ? data.description : '';
            document.getElementById('insurance_price_per_day').value = data ? (data.price_per_day !== null ? data.price_per_day : '') : '0';
            document.getElementById('insurance_price_one_time').value = data ? (data.price_one_time !== null ? data.price_one_time : '') : '';
            document.getElementById('insurance_is_daily').checked = data ? data.is_daily == 1 : true;
            document.getElementById('insurance_is_active').checked = data ? data.is_active == 1 : true;
            document.getElementById('insurance_sort_order').value = data ? data.sort_order : '0';
            
            const submitBtn = document.getElementById('insuranceSubmitBtn');
            if(data) {
                submitBtn.name = 'update_insurance';
                submitBtn.innerText = 'Update';
            } else {
                submitBtn.name = 'add_insurance';
                submitBtn.innerText = 'Add';
            }
            
            document.getElementById('insuranceModal').style.display = 'flex';
        }
        
        function editInsurance(data) {
            openInsuranceModal(data);
        }
        
        function deleteInsurance(id) {
            <?php if($is_worker): ?>
            alert('Workers cannot delete insurance types.');
            return;
            <?php endif; ?>
            
            if(confirm('Delete this insurance type? This cannot be undone.')) {
                window.location.href = `?delete_insurance=${id}&tab=insurance`;
            }
        }
        
        function openOptionModal(data = null) {
            <?php if($is_worker): ?>
            alert('Workers cannot add or edit options.');
            return;
            <?php endif; ?>
            
            document.getElementById('optionModalTitle').innerText = data ? 'Edit Additional Option' : 'Add Additional Option';
            document.getElementById('option_id').value = data ? data.id : '';
            document.getElementById('option_name').value = data ? data.name : '';
            document.getElementById('option_icon').value = data ? data.icon : '';
            document.getElementById('option_description').value = data ? data.description : '';
            document.getElementById('option_price_per_day').value = data ? (data.price_per_day !== null ? data.price_per_day : '') : '0';
            document.getElementById('option_price_one_time').value = data ? (data.price_one_time !== null ? data.price_one_time : '') : '';
            document.getElementById('option_is_daily').checked = data ? data.is_daily == 1 : true;
            document.getElementById('option_is_active').checked = data ? data.is_active == 1 : true;
            document.getElementById('option_max_quantity').value = data ? data.max_quantity : '1';
            document.getElementById('option_sort_order').value = data ? data.sort_order : '0';
            
            const submitBtn = document.getElementById('optionSubmitBtn');
            if(data) {
                submitBtn.name = 'update_option';
                submitBtn.innerText = 'Update';
            } else {
                submitBtn.name = 'add_option';
                submitBtn.innerText = 'Add';
            }
            
            document.getElementById('optionModal').style.display = 'flex';
        }
        
        function editOption(data) {
            openOptionModal(data);
        }
        
        function deleteOption(id) {
            <?php if($is_worker): ?>
            alert('Workers cannot delete options.');
            return;
            <?php endif; ?>
            
            if(confirm('Delete this option? This cannot be undone.')) {
                window.location.href = `?delete_option=${id}&tab=options`;
            }
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        window.onclick = function(e) {
            if(e.target.classList.contains('modal')) e.target.style.display = 'none';
        }
    </script>
</body>
</html>