<?php
$title = 'Add New Non-Lethal Weapon';
$active = 'non_lethal_weapons';
require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

$old = Session::get('old', []);
$errors = Session::get('errors', []);
$success = Session::get('success', '');
Session::remove('old');
Session::remove('errors');
Session::remove('success');
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-plus-circle"></i>
                Add New Non-Lethal Weapon
            </h1>
            <p>Enter non-lethal weapon details - All fields marked with * are required</p>
        </div>
        <div class="header-actions">
            <a href="<?php echo BASE_URL; ?>/non_lethal_weapons" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Non-Lethal Weapons
            </a>
        </div>
    </div>

    <!-- Success Message -->
    <?php if (!empty($success)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert" id="successAlert">
        <i class="fas fa-check-circle"></i>
        <?php echo Security::escape($success); ?>
        <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
    </div>
    <?php endif; ?>

    <!-- Form -->
    <div class="form-section">
        <form method="POST" action="<?php echo BASE_URL; ?>/non_lethal_weapons/store" id="weaponForm">
            <?php echo Security::csrfField(); ?>
            
            <!-- Weapon Identification -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-id-card"></i> Weapon Identification</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Weapon ID</label>
                        <input type="text" name="weapon_id" id="weapon_id" 
                               value="<?php echo Security::escape($old['weapon_id'] ?? ''); ?>" 
                               required maxlength="50" 
                               class="form-control <?php echo isset($errors['weapon_id']) ? 'error' : ''; ?>"
                               placeholder="e.g., NL-001">
                        <?php if (isset($errors['weapon_id'])): ?>
                            <small class="error-text"><?php echo $errors['weapon_id']; ?></small>
                        <?php endif; ?>
                        <small class="form-hint">Unique non-lethal weapon identifier</small>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Serial Number</label>
                        <input type="text" name="serial_no" id="serial_no" 
                               value="<?php echo Security::escape($old['serial_no'] ?? ''); ?>" 
                               required maxlength="100" 
                               class="form-control <?php echo isset($errors['serial_no']) ? 'error' : ''; ?>"
                               placeholder="Weapon serial number">
                        <?php if (isset($errors['serial_no'])): ?>
                            <small class="error-text"><?php echo $errors['serial_no']; ?></small>
                        <?php endif; ?>
                        <div id="serialValidation" class="form-hint"></div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Weapon Type</label>
                        <select name="weapon_type_id" id="weapon_type_id" 
                                class="form-control <?php echo isset($errors['weapon_type_id']) ? 'error' : ''; ?>">
                            <option value="">Select Type</option>
                            <?php foreach ($weaponTypes as $type): ?>
                            <option value="<?php echo $type['id']; ?>" 
                                    <?php echo ($old['weapon_type_id'] ?? '') == $type['id'] ? 'selected' : ''; ?>>
                                <?php echo Security::escape($type['type_name']); ?>
                            </option>
                            <?php endforeach; ?>
                            <option value="other">Other (Specify)</option>
                        </select>
                        <?php if (isset($errors['weapon_type_id'])): ?>
                            <small class="error-text"><?php echo $errors['weapon_type_id']; ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group" id="typeOtherWrapper" style="display: none;">
                        <label>Specify Weapon Type</label>
                        <input type="text" name="weapon_type_other" id="weapon_type_other" 
                               class="form-control" value="<?php echo Security::escape($old['weapon_type_other'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Make/Model</label>
                        <input type="text" name="make_model" value="<?php echo Security::escape($old['make_model'] ?? ''); ?>" 
                               required maxlength="255" 
                               class="form-control <?php echo isset($errors['make_model']) ? 'error' : ''; ?>"
                               placeholder="e.g., Taser X26P, Pepper Spray MK-4">
                        <?php if (isset($errors['make_model'])): ?>
                            <small class="error-text"><?php echo $errors['make_model']; ?></small>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Non-Lethal Weapon Specific Information -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-tag"></i> Non-Lethal Weapon Specifics</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Weapon Category</label>
                        <select name="weapon_category" id="weapon_category" required 
                                class="form-control <?php echo isset($errors['weapon_category']) ? 'error' : ''; ?>">
                            <option value="">Select Category</option>
                            <option value="Electrical" <?php echo ($old['weapon_category'] ?? '') == 'Electrical' ? 'selected' : ''; ?>>Electrical (Tasers, Stun Guns)</option>
                            <option value="Chemical" <?php echo ($old['weapon_category'] ?? '') == 'Chemical' ? 'selected' : ''; ?>>Chemical (Pepper Spray, Tear Gas)</option>
                            <option value="Kinetic" <?php echo ($old['weapon_category'] ?? '') == 'Kinetic' ? 'selected' : ''; ?>>Kinetic (Rubber Bullets, Bean Bags)</option>
                            <option value="Acoustic" <?php echo ($old['weapon_category'] ?? '') == 'Acoustic' ? 'selected' : ''; ?>>Acoustic (LRAD, Sonic Weapons)</option>
                            <option value="Restraint" <?php echo ($old['weapon_category'] ?? '') == 'Restraint' ? 'selected' : ''; ?>>Restraint (Handcuffs, Leg Irons)</option>
                            <option value="Other">Other</option>
                        </select>
                        <?php if (isset($errors['weapon_category'])): ?>
                            <small class="error-text"><?php echo $errors['weapon_category']; ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group" id="categoryOtherWrapper" style="display: none;">
                        <label>Specify Category</label>
                        <input type="text" name="weapon_category_other" id="weapon_category_other" 
                               class="form-control" value="<?php echo Security::escape($old['weapon_category_other'] ?? ''); ?>">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Effective Range (meters)</label>
                        <input type="number" name="effective_range" value="<?php echo Security::escape($old['effective_range'] ?? ''); ?>" 
                               step="0.1" min="0" max="1000"
                               class="form-control" placeholder="e.g., 10.5">
                        <small class="form-hint">Maximum effective range in meters</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Calibre/Ammunition Type</label>
                        <input type="text" name="ammunition_type" value="<?php echo Security::escape($old['ammunition_type'] ?? ''); ?>" 
                               maxlength="100" class="form-control"
                               placeholder="e.g., 9mm Rubber, Pepper Spray">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Power Source</label>
                        <select name="power_source" id="power_source" 
                                class="form-control">
                            <option value="">Select Power Source</option>
                            <option value="Battery" <?php echo ($old['power_source'] ?? '') == 'Battery' ? 'selected' : ''; ?>>Battery Operated</option>
                            <option value="Manual" <?php echo ($old['power_source'] ?? '') == 'Manual' ? 'selected' : ''; ?>>Manual/Mechanical</option>
                            <option value="Gas" <?php echo ($old['power_source'] ?? '') == 'Gas' ? 'selected' : ''; ?>>Gas Powered</option>
                            <option value="None" <?php echo ($old['power_source'] ?? '') == 'None' ? 'selected' : ''; ?>>None (Passive)</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Less-Lethal Rating</label>
                        <select name="less_lethal_rating" id="less_lethal_rating" 
                                class="form-control">
                            <option value="">Select Rating</option>
                            <option value="Low" <?php echo ($old['less_lethal_rating'] ?? '') == 'Low' ? 'selected' : ''; ?>>Low - Minimal risk</option>
                            <option value="Medium" <?php echo ($old['less_lethal_rating'] ?? '') == 'Medium' ? 'selected' : ''; ?>>Medium - Moderate risk</option>
                            <option value="High" <?php echo ($old['less_lethal_rating'] ?? '') == 'High' ? 'selected' : ''; ?>>High - Significant risk</option>
                        </select>
                        <small class="form-hint">Risk assessment rating</small>
                    </div>
                </div>
            </div>
            
            <!-- Source & Acquisition -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-truck"></i> Source & Acquisition</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Source</label>
                        <select name="source" id="source" required 
                                class="form-control <?php echo isset($errors['source']) ? 'error' : ''; ?>">
                            <option value="">Select Source</option>
                            <option value="FGN (NIS)" <?php echo ($old['source'] ?? '') == 'FGN (NIS)' ? 'selected' : ''; ?>>FGN (NIS)</option>
                            <option value="Donor" <?php echo ($old['source'] ?? '') == 'Donor' ? 'selected' : ''; ?>>Donor</option>
                            <option value="Transfer" <?php echo ($old['source'] ?? '') == 'Transfer' ? 'selected' : ''; ?>>Transfer</option>
                            <option value="Recovered" <?php echo ($old['source'] ?? '') == 'Recovered' ? 'selected' : ''; ?>>Recovered</option>
                            <option value="Other">Other</option>
                        </select>
                        <?php if (isset($errors['source'])): ?>
                            <small class="error-text"><?php echo $errors['source']; ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group" id="sourceOtherWrapper" style="display: none;">
                        <label>Specify Source</label>
                        <input type="text" name="source_other" id="source_other" 
                               class="form-control" value="<?php echo Security::escape($old['source_other'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>Date Acquired</label>
                        <input type="date" name="date_acquired" value="<?php echo Security::escape($old['date_acquired'] ?? ''); ?>" 
                               class="form-control" max="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
            </div>
            
            <!-- Current Status -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-clipboard-check"></i> Current Status</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Condition</label>
                        <select name="condition" required 
                                class="form-control <?php echo isset($errors['condition']) ? 'error' : ''; ?>">
                            <option value="">Select Condition</option>
                            <option value="Serviceable" <?php echo ($old['condition'] ?? '') == 'Serviceable' ? 'selected' : ''; ?>>Serviceable</option>
                            <option value="Unserviceable" <?php echo ($old['condition'] ?? '') == 'Unserviceable' ? 'selected' : ''; ?>>Unserviceable</option>
                        </select>
                        <?php if (isset($errors['condition'])): ?>
                            <small class="error-text"><?php echo $errors['condition']; ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Current Location</label>
                        <select name="current_location" id="current_location" required 
                                class="form-control <?php echo isset($errors['current_location']) ? 'error' : ''; ?>">
                            <option value="">Select Location</option>
                            <option value="Armoury" <?php echo ($old['current_location'] ?? '') == 'Armoury' ? 'selected' : ''; ?>>Armoury</option>
                            <option value="Issued" <?php echo ($old['current_location'] ?? '') == 'Issued' ? 'selected' : ''; ?>>Issued</option>
                            <option value="In Repair" <?php echo ($old['current_location'] ?? '') == 'In Repair' ? 'selected' : ''; ?>>In Repair</option>
                            <option value="Lost" <?php echo ($old['current_location'] ?? '') == 'Lost' ? 'selected' : ''; ?>>Lost</option>
                        </select>
                        <?php if (isset($errors['current_location'])): ?>
                            <small class="error-text"><?php echo $errors['current_location']; ?></small>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="form-row" id="custodianFields" style="<?php echo ($old['current_location'] ?? '') == 'Issued' ? '' : 'display: none;'; ?>">
                    <div class="form-group">
                        <label>Custodian Name</label>
                        <input type="text" name="custodian" value="<?php echo Security::escape($old['custodian'] ?? ''); ?>" 
                               maxlength="255" class="form-control">
                    </div>
                    
                    <div class="form-group">
                        <label>Custodian Rank</label>
                        <input type="text" name="custodian_rank" value="<?php echo Security::escape($old['custodian_rank'] ?? ''); ?>" 
                               maxlength="50" class="form-control">
                    </div>
                </div>
                
                <div class="form-row" id="custodianNisField" style="<?php echo ($old['current_location'] ?? '') == 'Issued' ? '' : 'display: none;'; ?>">
                    <div class="form-group">
                        <label>Custodian NIS Number</label>
                        <input type="text" name="custodian_nis" value="<?php echo Security::escape($old['custodian_nis'] ?? ''); ?>" 
                               maxlength="50" class="form-control">
                    </div>
                </div>
                
                <div class="form-group" id="locationOtherWrapper" style="<?php echo ($old['current_location'] ?? '') == 'Other' ? '' : 'display: none;'; ?>">
                    <label>Specify Location</label>
                    <input type="text" name="current_location_other" id="current_location_other" 
                           class="form-control" value="<?php echo Security::escape($old['current_location_other'] ?? ''); ?>">
                </div>
            </div>
            
            <!-- Inspection & Maintenance -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-clipboard-list"></i> Inspection & Maintenance</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Last Inspection Date</label>
                        <input type="date" name="last_inspection_date" value="<?php echo Security::escape($old['last_inspection_date'] ?? ''); ?>" 
                               class="form-control" max="<?php echo date('Y-m-d'); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>Next Inspection Date</label>
                        <input type="date" name="next_inspection_date" value="<?php echo Security::escape($old['next_inspection_date'] ?? ''); ?>" 
                               class="form-control">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Battery/Expiry Date (if applicable)</label>
                        <input type="date" name="expiry_date" value="<?php echo Security::escape($old['expiry_date'] ?? ''); ?>" 
                               class="form-control">
                        <small class="form-hint">For chemical agents or battery-powered devices</small>
                    </div>
                </div>
            </div>
            
            <!-- Remarks -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-sticky-note"></i> Remarks</h3>
                </div>
                
                <div class="form-group">
                    <textarea name="remarks" rows="3" class="form-control" 
                              placeholder="Any additional remarks about the non-lethal weapon"><?php echo Security::escape($old['remarks'] ?? ''); ?></textarea>
                </div>
            </div>
            
            <!-- Form Actions -->
            <div class="form-actions">
                <button type="submit" class="btn btn-success submit-btn" onclick="showSavingMessage(this)">
                    <i class="fas fa-save"></i> Save Non-Lethal Weapon
                </button>
                <button type="button" class="btn btn-secondary" onclick="resetForm('weaponForm')">
                    <i class="fas fa-undo"></i> Reset Form
                </button>
                <a href="<?php echo BASE_URL; ?>/non_lethal_weapons" class="btn btn-outline">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<style>
/* Alert Styles */
.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideIn 0.3s ease;
}

.alert-success {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
}

.alert i {
    font-size: 1.2rem;
}

.btn-close {
    margin-left: auto;
    background: none;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
    color: inherit;
    opacity: 0.7;
}

.btn-close:hover {
    opacity: 1;
}

@keyframes slideIn {
    from {
        transform: translateY(-20px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

/* Saving message overlay */
.saving-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    animation: fadeIn 0.3s ease;
}

.saving-message {
    background: white;
    padding: 30px;
    border-radius: 12px;
    text-align: center;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.saving-message i {
    font-size: 3rem;
    color: #e67e22;
    margin-bottom: 15px;
    animation: spin 1s linear infinite;
}

.saving-message p {
    font-size: 1.1rem;
    color: #333;
    margin: 0;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

/* Form styles */
.form-section {
    background: white;
    border-radius: 10px;
    padding: 25px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.form-section-inner {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--border-color);
}

.form-section-inner:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.section-title h3 {
    font-size: 1.1rem;
    margin: 0 0 20px 0;
    color: var(--primary-color);
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-group label {
    font-weight: 500;
    margin-bottom: 8px;
    font-size: 0.9rem;
    color: var(--text-primary);
}

.form-group label.required::after {
    content: '*';
    color: #e74c3c;
    margin-left: 4px;
}

.form-control {
    padding: 10px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 0.9rem;
    transition: all 0.3s;
}

.form-control:focus {
    outline: none;
    border-color: var(--secondary-color);
    box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.1);
}

.form-control.error {
    border-color: #e74c3c;
}

.error-text {
    color: #e74c3c;
    font-size: 0.75rem;
    margin-top: 5px;
}

.form-hint {
    color: #95a5a6;
    font-size: 0.7rem;
    margin-top: 5px;
}

.form-actions {
    display: flex;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
}

.btn-success {
    background: #e67e22;
    color: white;
}

.btn-success:hover {
    background: #d35400;
}

.btn-secondary {
    background: #95a5a6;
    color: white;
}

.btn-secondary:hover {
    background: #7f8c8d;
}

.btn-outline {
    background: transparent;
    border: 1px solid var(--border-color);
    color: var(--text-primary);
}

.btn-outline:hover {
    background: var(--light-bg);
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
        gap: 15px;
    }
    
    .form-actions {
        flex-direction: column;
    }
    
    .btn {
        width: 100%;
        justify-content: center;
    }
}
</style>

<script>
function showSavingMessage(button) {
    const overlay = document.createElement('div');
    overlay.className = 'saving-overlay';
    overlay.id = 'savingOverlay';
    overlay.innerHTML = `
        <div class="saving-message">
            <i class="fas fa-spinner fa-pulse"></i>
            <p>Saving non-lethal weapon... Please wait</p>
        </div>
    `;
    document.body.appendChild(overlay);
    
    button.disabled = true;
    document.getElementById('weaponForm').submit();
}

document.addEventListener('DOMContentLoaded', function() {
    // Weapon type other field
    const typeSelect = document.getElementById('weapon_type_id');
    const typeWrapper = document.getElementById('typeOtherWrapper');
    const typeOther = document.getElementById('weapon_type_other');
    
    if (typeSelect) {
        typeSelect.addEventListener('change', function() {
            if (this.value === 'other') {
                typeWrapper.style.display = 'block';
                typeOther.required = true;
            } else {
                typeWrapper.style.display = 'none';
                typeOther.required = false;
                typeOther.value = '';
            }
        });
        
        <?php if (($old['weapon_type_id'] ?? '') === 'other'): ?>
        typeSelect.value = 'other';
        typeWrapper.style.display = 'block';
        <?php endif; ?>
    }
    
    // Weapon category other field
    const categorySelect = document.getElementById('weapon_category');
    const categoryWrapper = document.getElementById('categoryOtherWrapper');
    const categoryOther = document.getElementById('weapon_category_other');
    
    if (categorySelect) {
        categorySelect.addEventListener('change', function() {
            if (this.value === 'Other') {
                categoryWrapper.style.display = 'block';
                categoryOther.required = true;
            } else {
                categoryWrapper.style.display = 'none';
                categoryOther.required = false;
                categoryOther.value = '';
            }
        });
        
        <?php if (($old['weapon_category'] ?? '') === 'Other'): ?>
        categorySelect.value = 'Other';
        categoryWrapper.style.display = 'block';
        <?php endif; ?>
    }
    
    // Source other field
    const sourceSelect = document.getElementById('source');
    const sourceWrapper = document.getElementById('sourceOtherWrapper');
    const sourceOther = document.getElementById('source_other');
    
    if (sourceSelect) {
        sourceSelect.addEventListener('change', function() {
            if (this.value === 'Other') {
                sourceWrapper.style.display = 'block';
                sourceOther.required = true;
            } else {
                sourceWrapper.style.display = 'none';
                sourceOther.required = false;
                sourceOther.value = '';
            }
        });
        
        <?php if (($old['source'] ?? '') === 'Other'): ?>
        sourceSelect.value = 'Other';
        sourceWrapper.style.display = 'block';
        <?php endif; ?>
    }
    
    // Location dependent fields
    const locationSelect = document.getElementById('current_location');
    const custodianFields = document.getElementById('custodianFields');
    const custodianNisField = document.getElementById('custodianNisField');
    const locationWrapper = document.getElementById('locationOtherWrapper');
    const locationOther = document.getElementById('current_location_other');
    
    if (locationSelect) {
        locationSelect.addEventListener('change', function() {
            if (this.value === 'Issued') {
                custodianFields.style.display = 'flex';
                custodianNisField.style.display = 'flex';
            } else {
                custodianFields.style.display = 'none';
                custodianNisField.style.display = 'none';
            }
            
            if (this.value === 'Other') {
                locationWrapper.style.display = 'block';
                locationOther.required = true;
            } else {
                locationWrapper.style.display = 'none';
                locationOther.required = false;
                locationOther.value = '';
            }
        });
        
        <?php if (($old['current_location'] ?? '') === 'Issued'): ?>
        locationSelect.value = 'Issued';
        custodianFields.style.display = 'flex';
        custodianNisField.style.display = 'flex';
        <?php elseif (($old['current_location'] ?? '') === 'Other'): ?>
        locationSelect.value = 'Other';
        locationWrapper.style.display = 'block';
        <?php endif; ?>
    }
    
    // Serial number validation
    const serialInput = document.getElementById('serial_no');
    const serialValidation = document.getElementById('serialValidation');
    let serialTimeout;
    
    if (serialInput) {
        serialInput.addEventListener('input', function() {
            clearTimeout(serialTimeout);
            const serial = this.value;
            
            if (serial.length < 3) {
                serialValidation.innerHTML = '';
                return;
            }
            
            serialTimeout = setTimeout(() => {
                fetch('<?php echo BASE_URL; ?>/api/validate_serial?type=non_lethal&serial=' + encodeURIComponent(serial))
                    .then(response => response.json())
                    .then(data => {
                        if (data.exists) {
                            serialValidation.innerHTML = '<span class="text-danger"><i class="fas fa-times-circle"></i> Serial number already exists</span>';
                            serialInput.classList.add('error');
                        } else {
                            serialValidation.innerHTML = '<span class="text-success"><i class="fas fa-check-circle"></i> Serial number available</span>';
                            serialInput.classList.remove('error');
                        }
                    });
            }, 500);
        });
    }
    
    // Auto-hide success message after 5 seconds
    const successAlert = document.getElementById('successAlert');
    if (successAlert) {
        setTimeout(function() {
            successAlert.style.display = 'none';
        }, 5000);
    }
});

function resetForm(formId) {
    if (confirm('Are you sure you want to reset the form? All unsaved data will be lost.')) {
        document.getElementById(formId).reset();
        
        document.getElementById('typeOtherWrapper').style.display = 'none';
        document.getElementById('categoryOtherWrapper').style.display = 'none';
        document.getElementById('sourceOtherWrapper').style.display = 'none';
        document.getElementById('locationOtherWrapper').style.display = 'none';
        document.getElementById('custodianFields').style.display = 'none';
        document.getElementById('custodianNisField').style.display = 'none';
        
        if (typeof showNotification === 'function') {
            showNotification('info', 'Form has been reset');
        } else {
            alert('Form has been reset');
        }
    }
}
</script>

<?php require_once __DIR__ . '/../layouts/footer.php'; ?>