<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check permissions
/*$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT HasPermission(?, 'agents_edit') as has_permission");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$permission_result = $stmt->get_result()->fetch_assoc();

if (!$permission_result['has_permission']) {
    header('Location: index.php?error=no_permission');
    exit();
}*/

// Get agent ID from URL
$agent_id = $_GET['id'] ?? 0;
if (!$agent_id) {
    header('Location: list_agents.php');
    exit();
}

$errors = [];
$success_message = '';

// Get existing agent data
$agent_sql = "SELECT u.*, ur.role_name 
              FROM users u 
              INNER JOIN user_roles ur ON u.role_id = ur.role_id
              WHERE u.user_id = ? AND u.agent_code IS NOT NULL";
$agent_stmt = $conn->prepare($agent_sql);
$agent_stmt->bind_param("i", $agent_id);
$agent_stmt->execute();
$agent = $agent_stmt->get_result()->fetch_assoc();

if (!$agent) {
    header('Location: list_agents.php?error=agent_not_found');
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate and sanitize input
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone_number = trim($_POST['phone_number']);
    $role_id = (int)$_POST['role_id'];
    $branch_id = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
    $supervisor_id = !empty($_POST['supervisor_id']) ? (int)$_POST['supervisor_id'] : null;
    $license_number = trim($_POST['license_number']);
    $license_expiry = !empty($_POST['license_expiry']) ? $_POST['license_expiry'] : null;
    $commission_rate = (float)$_POST['commission_rate'];
    $target_monthly = (float)$_POST['target_monthly'];
    $date_of_birth = !empty($_POST['date_of_birth']) ? $_POST['date_of_birth'] : null;
    $gender = $_POST['gender'];
    $national_id = trim($_POST['national_id']);
    $address = trim($_POST['address']);
    $emergency_contact = trim($_POST['emergency_contact']);
    $emergency_phone = trim($_POST['emergency_phone']);
    $status = $_POST['status'];

    // Validation
    if (empty($full_name)) $errors[] = "Full name is required";
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email is required";
    if (empty($role_id)) $errors[] = "Role is required";
    if ($commission_rate < 0 || $commission_rate > 100) $errors[] = "Commission rate must be between 0 and 100";

    // Check for existing email (excluding current agent)
    if (empty($errors)) {
        $check_sql = "SELECT COUNT(*) as count FROM users WHERE email = ? AND user_id != ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("si", $email, $agent_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result()->fetch_assoc();
        
        if ($check_result['count'] > 0) {
            $errors[] = "Email already exists for another user";
        }
    }

    // Update agent information
    if (empty($errors)) {
        $conn->begin_transaction();
        
        try {
            // Store old values for logging
            $old_values = [
                'full_name' => $agent['full_name'],
                'email' => $agent['email'],
                'phone_number' => $agent['phone_number'],
                'role_id' => $agent['role_id'],
                'branch_id' => $agent['branch_id'],
                'supervisor_id' => $agent['supervisor_id'],
                'license_number' => $agent['license_number'],
                'license_expiry' => $agent['license_expiry'],
                'commission_rate' => $agent['commission_rate'],
                'target_monthly' => $agent['target_monthly'],
                'status' => $agent['status']
            ];

            // Update user
            $update_sql = "UPDATE users SET 
                full_name = ?, email = ?, phone_number = ?, role_id = ?, 
                branch_id = ?, supervisor_id = ?, license_number = ?, license_expiry = ?, 
                commission_rate = ?, target_monthly = ?, date_of_birth = ?, gender = ?, 
                national_id = ?, address = ?, emergency_contact = ?, emergency_phone = ?, 
                status = ?, updated_at = CURRENT_TIMESTAMP 
                WHERE user_id = ?";
            
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("sssiiissddsssssssi", 
                $full_name, $email, $phone_number, $role_id, $branch_id, $supervisor_id,
                $license_number, $license_expiry, $commission_rate, $target_monthly,
                $date_of_birth, $gender, $national_id, $address, $emergency_contact, 
                $emergency_phone, $status, $agent_id
            );
            
            if ($update_stmt->execute()) {
                // Log activity
                $new_values = [
                    'full_name' => $full_name,
                    'email' => $email,
                    'phone_number' => $phone_number,
                    'role_id' => $role_id,
                    'branch_id' => $branch_id,
                    'supervisor_id' => $supervisor_id,
                    'license_number' => $license_number,
                    'license_expiry' => $license_expiry,
                    'commission_rate' => $commission_rate,
                    'target_monthly' => $target_monthly,
                    'status' => $status,
                    'updated_by' => $_SESSION['full_name']
                ];

                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values) 
                           VALUES (?, 'UPDATE', 'AGENT', ?, 'USER', ?, ?)";
                $log_stmt = $conn->prepare($log_sql);
                $old_values_json = json_encode($old_values);
                $new_values_json = json_encode($new_values);
                $log_stmt->bind_param("iiss", $user_id, $agent_id, $old_values_json, $new_values_json);
                $log_stmt->execute();
                
                $conn->commit();
                
                $success_message = "Agent information updated successfully!";
                
                // Refresh agent data
                $agent_stmt->execute();
                $agent = $agent_stmt->get_result()->fetch_assoc();
                
            } else {
                throw new Exception("Failed to update agent information");
            }
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Error updating agent: " . $e->getMessage();
        }
    }
}

// Get branches for dropdown
$branches_sql = "SELECT branch_id, branch_name FROM branches WHERE is_active = 1 ORDER BY branch_name";
$branches_result = $conn->query($branches_sql);

// Get agent roles for dropdown
$roles_sql = "SELECT role_id, role_name FROM user_roles WHERE role_name LIKE '%Agent%' ORDER BY role_name";
$roles_result = $conn->query($roles_sql);

// Get supervisors (agents and managers)
$supervisors_sql = "SELECT u.user_id, u.full_name, u.agent_code, ur.role_name 
                   FROM users u 
                   INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                   WHERE u.status = 'ACTIVE' 
                   AND (ur.role_name LIKE '%Supervisor%' OR ur.role_name LIKE '%Manager%' OR ur.role_name LIKE '%Senior%')
                   AND u.user_id != ?
                   ORDER BY u.full_name";
$supervisors_stmt = $conn->prepare($supervisors_sql);
$supervisors_stmt->bind_param("i", $agent_id);
$supervisors_stmt->execute();
$supervisors_result = $supervisors_stmt->get_result();

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Agent - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .form-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .form-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0;
            padding: 25px;
        }
        .form-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .section-title {
            color: #495057;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e9ecef;
        }
        .required-field {
            color: #dc3545;
        }
        .agent-info-bar {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .status-badge {
            font-size: 0.8rem;
            padding: 5px 12px;
            border-radius: 15px;
            font-weight: 600;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Edit Agent</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_agents.php">Agents</a></li>
                                        <li class="breadcrumb-item active">Edit Agent</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Display Messages -->
                    <?php if (!empty($errors)): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <i class="ri-error-warning-line me-2"></i>
                                    <strong>Please correct the following errors:</strong>
                                    <ul class="mb-0 mt-2">
                                        <?php foreach ($errors as $error): ?>
                                            <li><?php echo htmlspecialchars($error); ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                    <i class="ri-checkbox-circle-line me-2"></i>
                                    <?php echo htmlspecialchars($success_message); ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Agent Information Bar -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="agent-info-bar">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm bg-primary text-white rounded-circle me-3 d-flex align-items-center justify-content-center">
                                            <?php echo strtoupper(substr($agent['full_name'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <h5 class="mb-1"><?php echo htmlspecialchars($agent['full_name']); ?></h5>
                                            <p class="mb-0 text-muted">
                                                Agent Code: <?php echo htmlspecialchars($agent['agent_code']); ?> | 
                                                Role: <?php echo htmlspecialchars($agent['role_name']); ?>
                                            </p>
                                        </div>
                                    </div>
                                    <div class="d-flex gap-2">
                                        <?php 
                                        $status_class = match($agent['status']) {
                                            'ACTIVE' => 'bg-success',
                                            'INACTIVE' => 'bg-secondary',
                                            'SUSPENDED' => 'bg-danger',
                                            'PENDING' => 'bg-warning',
                                            default => 'bg-info'
                                        };
                                        ?>
                                        <span class="status-badge <?php echo $status_class; ?> text-white">
                                            <?php echo ucfirst(strtolower($agent['status'])); ?>
                                        </span>
                                        <a href="view_agent.php?id=<?php echo $agent['user_id']; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="ri-eye-line me-1"></i> View Profile
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Edit Form -->
                    <div class="row justify-content-center">
                        <div class="col-xl-10">
                            <form method="POST" id="editAgentForm" novalidate>
                                
                                <!-- Basic Information -->
                                <div class="form-section">
                                    <h5 class="section-title">
                                        <i class="ri-user-line me-2"></i>Basic Information
                                    </h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Full Name <span class="required-field">*</span></label>
                                            <input type="text" class="form-control" name="full_name" 
                                                   value="<?php echo htmlspecialchars($agent['full_name']); ?>" required>
                                            <div class="invalid-feedback">Please provide a valid full name.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Email Address <span class="required-field">*</span></label>
                                            <input type="email" class="form-control" name="email" 
                                                   value="<?php echo htmlspecialchars($agent['email']); ?>" required>
                                            <div class="invalid-feedback">Please provide a valid email address.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Phone Number</label>
                                            <input type="tel" class="form-control" name="phone_number" 
                                                   value="<?php echo htmlspecialchars($agent['phone_number']); ?>"
                                                   placeholder="+254 700 000 000">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">National ID</label>
                                            <input type="text" class="form-control" name="national_id" 
                                                   value="<?php echo htmlspecialchars($agent['national_id']); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Date of Birth</label>
                                            <input type="date" class="form-control" name="date_of_birth" 
                                                   value="<?php echo htmlspecialchars($agent['date_of_birth']); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Gender</label>
                                            <select class="form-select" name="gender">
                                                <option value="">Select Gender</option>
                                                <option value="MALE" <?php echo $agent['gender'] == 'MALE' ? 'selected' : ''; ?>>Male</option>
                                                <option value="FEMALE" <?php echo $agent['gender'] == 'FEMALE' ? 'selected' : ''; ?>>Female</option>
                                                <option value="OTHER" <?php echo $agent['gender'] == 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                            </select>
                                        </div>
                                        <div class="col-12 mb-3">
                                            <label class="form-label">Address</label>
                                            <textarea class="form-control" name="address" rows="3"><?php echo htmlspecialchars($agent['address']); ?></textarea>
                                        </div>
                                    </div>
                                </div>

                                <!-- Role & Organization Information -->
                                <div class="form-section">
                                    <h5 class="section-title">
                                        <i class="ri-shield-user-line me-2"></i>Role & Organization
                                    </h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Role <span class="required-field">*</span></label>
                                            <select class="form-select" name="role_id" required>
                                                <option value="">Select Role</option>
                                                <?php while($role = $roles_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $role['role_id']; ?>" 
                                                            <?php echo $agent['role_id'] == $role['role_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($role['role_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                            <div class="invalid-feedback">Please select a role.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="ACTIVE" <?php echo $agent['status'] == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                <option value="INACTIVE" <?php echo $agent['status'] == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                                <option value="SUSPENDED" <?php echo $agent['status'] == 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                                <option value="PENDING" <?php echo $agent['status'] == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Branch</label>
                                            <select class="form-select" name="branch_id">
                                                <option value="">Select Branch</option>
                                                <?php while($branch = $branches_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $branch['branch_id']; ?>" 
                                                            <?php echo $agent['branch_id'] == $branch['branch_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($branch['branch_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Supervisor</label>
                                            <select class="form-select" name="supervisor_id">
                                                <option value="">Select Supervisor</option>
                                                <?php while($supervisor = $supervisors_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $supervisor['user_id']; ?>" 
                                                            <?php echo $agent['supervisor_id'] == $supervisor['user_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($supervisor['full_name']); ?>
                                                        <?php if($supervisor['agent_code']): ?>
                                                            (<?php echo htmlspecialchars($supervisor['agent_code']); ?>)
                                                        <?php endif; ?>
                                                        - <?php echo htmlspecialchars($supervisor['role_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <!-- Professional Information -->
                                <div class="form-section">
                                    <h5 class="section-title">
                                        <i class="ri-briefcase-line me-2"></i>Professional Information
                                    </h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">License Number</label>
                                            <input type="text" class="form-control" name="license_number" 
                                                   value="<?php echo htmlspecialchars($agent['license_number']); ?>"
                                                   placeholder="e.g., IRA/AGT/2024/001">
                                            <div class="form-text">Insurance Regulatory Authority license number</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">License Expiry Date</label>
                                            <input type="date" class="form-control" name="license_expiry" 
                                                   value="<?php echo htmlspecialchars($agent['license_expiry']); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Commission Rate (%)</label>
                                            <input type="number" class="form-control" name="commission_rate" 
                                                   value="<?php echo htmlspecialchars($agent['commission_rate']); ?>"
                                                   min="0" max="100" step="0.1">
                                            <div class="form-text">Commission percentage (0-100)</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Monthly Target (KSH)</label>
                                            <input type="number" class="form-control" name="target_monthly" 
                                                   value="<?php echo htmlspecialchars($agent['target_monthly']); ?>"
                                                   min="0" step="1000">
                                            <div class="form-text">Monthly sales target in KSH</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Emergency Contact Name</label>
                                            <input type="text" class="form-control" name="emergency_contact" 
                                                   value="<?php echo htmlspecialchars($agent['emergency_contact']); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Emergency Contact Phone</label>
                                            <input type="tel" class="form-control" name="emergency_phone" 
                                                   value="<?php echo htmlspecialchars($agent['emergency_phone']); ?>"
                                                   placeholder="+254 700 000 000">
                                        </div>
                                    </div>
                                </div>

                                <!-- Form Actions -->
                                <div class="form-section">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <a href="list_agents.php" class="btn btn-secondary">
                                                <i class="ri-arrow-left-line me-1"></i> Back to Agents
                                            </a>
                                            <a href="view_agent.php?id=<?php echo $agent['user_id']; ?>" class="btn btn-outline-primary ms-2">
                                                <i class="ri-eye-line me-1"></i> View Profile
                                            </a>
                                        </div>
                                        <div>
                                            <button type="button" class="btn btn-outline-warning me-2" onclick="resetForm()">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </button>
                                            <button type="submit" class="btn btn-success" id="submitBtn">
                                                <i class="ri-save-line me-1"></i> Update Agent
                                            </button>
                                        </div>
                                    </div>
                                </div>

                            </form>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
    $(document).ready(function() {
        // Form validation
        $('#editAgentForm').on('submit', function(e) {
            const form = this;
            let isValid = true;
            
            // Reset validation states
            $(form).removeClass('was-validated');
            
            // Check required fields
            $(form).find('input[required], select[required]').each(function() {
                if (!$(this).val().trim()) {
                    $(this).addClass('is-invalid');
                    isValid = false;
                } else {
                    $(this).removeClass('is-invalid');
                    $(this).addClass('is-valid');
                }
            });
            
            // Check email format
            const email = $('input[name="email"]').val();
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (email && !emailRegex.test(email)) {
                $('input[name="email"]').addClass('is-invalid');
                isValid = false;
            }
            
            // Check commission rate
            const commissionRate = parseFloat($('input[name="commission_rate"]').val());
            if (commissionRate < 0 || commissionRate > 100) {
                $('input[name="commission_rate"]').addClass('is-invalid');
                isValid = false;
            }
            
            if (!isValid) {
                e.preventDefault();
                $(form).addClass('was-validated');
                
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    text: 'Please fill in all required fields correctly.'
                });
                return;
            }
            
            // Show loading state
            const submitBtn = $('#submitBtn');
            submitBtn.html('<span class="spinner-border spinner-border-sm me-2"></span>Updating...');
            submitBtn.prop('disabled', true);
        });
        
        // Real-time validation
        $('input[required], select[required]').on('blur', function() {
            if ($(this).val().trim()) {
                $(this).removeClass('is-invalid');
                $(this).addClass('is-valid');
            } else {
                $(this).removeClass('is-valid');
                $(this).addClass('is-invalid');
            }
        });
        
        // Email validation
        $('input[name="email"]').on('blur', function() {
            const email = $(this).val();
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (email && emailRegex.test(email)) {
                $(this).removeClass('is-invalid');
                $(this).addClass('is-valid');
            } else if (email) {
                $(this).removeClass('is-valid');
                $(this).addClass('is-invalid');
            }
        });
        
        // Commission rate validation
        $('input[name="commission_rate"]').on('input', function() {
            const rate = parseFloat($(this).val());
            if (rate >= 0 && rate <= 100) {
                $(this).removeClass('is-invalid');
                $(this).addClass('is-valid');
            } else {
                $(this).removeClass('is-valid');
                $(this).addClass('is-invalid');
            }
        });
    });
    
    function resetForm() {
        Swal.fire({
            title: 'Reset Form?',
            text: 'This will reset all changes and reload the original data.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, reset it!'
        }).then((result) => {
            if (result.isConfirmed) {
                location.reload();
            }
        });
    }
    
    // Auto-save functionality (optional)
    let autoSaveTimeout;
    $('input, select, textarea').on('input change', function() {
        clearTimeout(autoSaveTimeout);
        autoSaveTimeout = setTimeout(function() {
            // Could implement auto-save to drafts here
            console.log('Auto-save triggered');
        }, 5000); // 5 seconds delay
    });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>