<?php
$title = 'Add New Weapon';
$active = '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', '');
$error = Session::get('error', ''); // Add this to get error messages
Session::remove('old');
Session::remove('errors');
Session::remove('success');
Session::remove('error');

// Get zones and commands for dropdowns
$zones = Database::fetchAll("SELECT id, zone_name FROM zones ORDER BY zone_name");
if ($zones === false) $zones = [];

// Get all commands for initial load (will be filtered by zone via JS)
$allCommands = Database::fetchAll("SELECT id, command_name, zone_id FROM commands ORDER BY command_name");
if ($allCommands === false) $allCommands = [];
?>

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

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

    <!-- Validation Errors -->
    <?php if (!empty($errors)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-triangle"></i>
        <strong>Please fix the following errors:</strong>
        <ul style="margin-top: 10px; margin-bottom: 0;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo Security::escape($error); ?></li>
            <?php endforeach; ?>
        </ul>
        <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; ?>/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., ARM-001">
                        <?php if (isset($errors['weapon_id'])): ?>
                            <small class="error-text"><?php echo $errors['weapon_id']; ?></small>
                        <?php endif; ?>
                        <small class="form-hint">Unique 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., Beretta 92FS">
                        <?php if (isset($errors['make_model'])): ?>
                            <small class="error-text"><?php echo $errors['make_model']; ?></small>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Calibre Information -->
            <div class="form-row">
                <div class="form-group">
                    <label>Calibre</label>
                    <select name="calibre_id" id="calibre_id" 
                            class="form-control <?php echo isset($errors['calibre_id']) ? 'error' : ''; ?>">
                        <option value="">Select Calibre</option>
                        <?php foreach ($calibres as $calibre): ?>
                        <option value="<?php echo $calibre['id']; ?>" 
                                <?php echo ($old['calibre_id'] ?? '') == $calibre['id'] ? 'selected' : ''; ?>>
                            <?php echo Security::escape($calibre['calibre_name']); ?>
                        </option>
                        <?php endforeach; ?>
                        <option value="other">Other (Specify)</option>
                    </select>
                    <?php if (isset($errors['calibre_id'])): ?>
                        <small class="error-text"><?php echo $errors['calibre_id']; ?></small>
                    <?php endif; ?>
                </div>
                
                <div class="form-group" id="calibreOtherWrapper" style="display: none;">
                    <label>Specify Calibre</label>
                    <input type="text" name="calibre_other" id="calibre_other" 
                           class="form-control" value="<?php echo Security::escape($old['calibre_other'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <!--Empty 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="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>
                
                <!-- Issued Fields -->
                <div id="issuedFields" class="conditional-fields" style="<?php echo ($old['current_location'] ?? '') == 'Issued' ? 'display: block;' : 'display: none;'; ?>">
                    <div class="section-title" style="margin-top: 20px;">
                        <h3><i class="fas fa-user-check"></i> Issued To Details</h3>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Custodian Name</label>
                            <input type="text" name="custodian" id="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" id="custodian_rank" 
                                   value="<?php echo Security::escape($old['custodian_rank'] ?? ''); ?>" 
                                   maxlength="50" class="form-control">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Custodian NIS Number</label>
                            <input type="text" name="custodian_nis" id="custodian_nis" 
                                   value="<?php echo Security::escape($old['custodian_nis'] ?? ''); ?>" 
                                   maxlength="50" class="form-control">
                        </div>
                        
                        <div class="form-group">
                            <label>Custodian Phone Number</label>
                            <input type="text" name="custodian_phone" id="custodian_phone" 
                                   value="<?php echo Security::escape($old['custodian_phone'] ?? ''); ?>" 
                                   maxlength="20" class="form-control"
                                   placeholder="e.g., 08012345678">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Custodian Zone</label>
                            <select name="custodian_zone_id" id="custodian_zone_id" class="form-control">
                                <option value="">Select Zone</option>
                                <?php foreach ($zones as $zone): ?>
                                <option value="<?php echo $zone['id']; ?>" 
                                        data-zone-name="<?php echo Security::escape($zone['zone_name']); ?>"
                                        <?php echo ($old['custodian_zone_id'] ?? '') == $zone['id'] ? 'selected' : ''; ?>>
                                    <?php echo Security::escape($zone['zone_name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Custodian Command</label>
                            <select name="custodian_command_id" id="custodian_command_id" class="form-control">
                                <option value="">Select Zone First</option>
                                <?php if (!empty($old['custodian_command_id'])): ?>
                                <?php foreach ($allCommands as $cmd): ?>
                                <?php if ($cmd['id'] == $old['custodian_command_id']): ?>
                                <option value="<?php echo $cmd['id']; ?>" selected><?php echo Security::escape($cmd['command_name']); ?></option>
                                <?php endif; ?>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Lost Fields -->
                <div id="lostFields" class="conditional-fields" style="<?php echo ($old['current_location'] ?? '') == 'Lost' ? 'display: block;' : 'display: none;'; ?>">
                    <div class="section-title" style="margin-top: 20px;">
                        <h3><i class="fas fa-search"></i> Loss Details</h3>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Person Who Lost Weapon - Name</label>
                            <input type="text" name="lost_by_name" id="lost_by_name" 
                                   value="<?php echo Security::escape($old['lost_by_name'] ?? ''); ?>" 
                                   maxlength="255" class="form-control"
                                   placeholder="Full name of person who lost the weapon">
                        </div>
                        
                        <div class="form-group">
                            <label>Person's Rank</label>
                            <input type="text" name="lost_by_rank" id="lost_by_rank" 
                                   value="<?php echo Security::escape($old['lost_by_rank'] ?? ''); ?>" 
                                   maxlength="50" class="form-control"
                                   placeholder="Rank">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>NIS Number</label>
                            <input type="text" name="lost_by_nis" id="lost_by_nis" 
                                   value="<?php echo Security::escape($old['lost_by_nis'] ?? ''); ?>" 
                                   maxlength="50" class="form-control"
                                   placeholder="NIS Number">
                        </div>
                        
                        <div class="form-group">
                            <label>Phone Number</label>
                            <input type="text" name="lost_by_phone" id="lost_by_phone" 
                                   value="<?php echo Security::escape($old['lost_by_phone'] ?? ''); ?>" 
                                   maxlength="20" class="form-control"
                                   placeholder="Phone number">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Zone</label>
                            <select name="lost_zone_id" id="lost_zone_id" class="form-control">
                                <option value="">Select Zone</option>
                                <?php foreach ($zones as $zone): ?>
                                <option value="<?php echo $zone['id']; ?>" 
                                        data-zone-name="<?php echo Security::escape($zone['zone_name']); ?>"
                                        <?php echo ($old['lost_zone_id'] ?? '') == $zone['id'] ? 'selected' : ''; ?>>
                                    <?php echo Security::escape($zone['zone_name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Command</label>
                            <select name="lost_command_id" id="lost_command_id" class="form-control">
                                <option value="">Select Zone First</option>
                                <?php if (!empty($old['lost_command_id'])): ?>
                                <?php foreach ($allCommands as $cmd): ?>
                                <?php if ($cmd['id'] == $old['lost_command_id']): ?>
                                <option value="<?php echo $cmd['id']; ?>" selected><?php echo Security::escape($cmd['command_name']); ?></option>
                                <?php endif; ?>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Date of Loss</label>
                            <input type="date" name="loss_date" id="loss_date" 
                                   value="<?php echo Security::escape($old['loss_date'] ?? ''); ?>" 
                                   class="form-control" max="<?php echo date('Y-m-d'); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label>Incident Report Number</label>
                            <input type="text" name="loss_report_no" id="loss_report_no" 
                                   value="<?php echo Security::escape($old['loss_report_no'] ?? ''); ?>" 
                                   maxlength="100" class="form-control"
                                   placeholder="Police/Internal incident report number">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Circumstances of Loss</label>
                        <textarea name="loss_circumstances" id="loss_circumstances" rows="3" 
                                  class="form-control" 
                                  placeholder="Describe how, when, and where the weapon was lost..."><?php echo Security::escape($old['loss_circumstances'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Action Taken</label>
                        <textarea name="loss_action_taken" id="loss_action_taken" rows="2" 
                                  class="form-control" 
                                  placeholder="Describe any action taken (e.g., police report, internal investigation, etc.)"><?php echo Security::escape($old['loss_action_taken'] ?? ''); ?></textarea>
                    </div>
                </div>
                
                <div class="form-group" id="locationOtherWrapper" style="<?php echo ($old['current_location'] ?? '') == 'Other' ? 'display: block;' : '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 -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-clipboard-list"></i> Inspection</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>
            
            <!-- 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 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">
                    <i class="fas fa-save"></i> Save 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; ?>/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-danger {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
}

.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;
    }
}

/* Conditional Fields Styling */
.conditional-fields {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    margin-top: 15px;
    margin-bottom: 15px;
    border-left: 4px solid #3498db;
}

.conditional-fields .section-title h3 {
    font-size: 1.1rem;
    margin-bottom: 15px;
    color: #2c3e50;
}

/* Form Row for flex layouts */
.form-row {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

.form-row .form-group {
    flex: 1;
    min-width: 200px;
}

.error-text {
    color: #dc3545;
    font-size: 0.875rem;
    margin-top: 5px;
    display: block;
}

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

@media (max-width: 768px) {
    .form-row {
        flex-direction: column;
        gap: 10px;
    }
}
</style>

<script>
// Define base URL
const baseUrl = '<?php echo BASE_URL; ?>';
const allCommands = <?php echo json_encode($allCommands); ?>;

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; ?>
    }
    
    // Calibre other field
    const calibreSelect = document.getElementById('calibre_id');
    const calibreWrapper = document.getElementById('calibreOtherWrapper');
    const calibreOther = document.getElementById('calibre_other');
    
    if (calibreSelect) {
        calibreSelect.addEventListener('change', function() {
            if (this.value === 'other') {
                calibreWrapper.style.display = 'block';
                calibreOther.required = true;
            } else {
                calibreWrapper.style.display = 'none';
                calibreOther.required = false;
                calibreOther.value = '';
            }
        });
        
        <?php if (($old['calibre_id'] ?? '') === 'other'): ?>
        calibreSelect.value = 'other';
        calibreWrapper.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; ?>
    }
    
    // Function to populate commands based on zone selection
    function populateCommands(zoneId, commandSelectId, selectedCommandId = null) {
        const commandSelect = document.getElementById(commandSelectId);
        if (!commandSelect) return;
        
        // Filter commands by zone
        const filteredCommands = allCommands.filter(cmd => cmd.zone_id == zoneId);
        
        commandSelect.innerHTML = '<option value="">Select Command</option>';
        
        if (filteredCommands.length > 0) {
            filteredCommands.forEach(cmd => {
                const option = document.createElement('option');
                option.value = cmd.id;
                option.textContent = cmd.command_name;
                if (selectedCommandId && selectedCommandId == cmd.id) {
                    option.selected = true;
                }
                commandSelect.appendChild(option);
            });
        } else {
            commandSelect.innerHTML = '<option value="">No commands found for this zone</option>';
        }
    }
    
    // Location dependent fields
    const locationSelect = document.getElementById('current_location');
    const issuedFields = document.getElementById('issuedFields');
    const lostFields = document.getElementById('lostFields');
    const locationWrapper = document.getElementById('locationOtherWrapper');
    
    // Function to toggle conditional fields based on selected location
    function toggleLocationFields() {
        const selectedValue = locationSelect.value;
        
        if (issuedFields) issuedFields.style.display = 'none';
        if (lostFields) lostFields.style.display = 'none';
        if (locationWrapper) locationWrapper.style.display = 'none';
        
        if (selectedValue === 'Issued') {
            if (issuedFields) issuedFields.style.display = 'block';
            // Clear lost fields when not needed
            if (document.getElementById('loss_date')) document.getElementById('loss_date').value = '';
            if (document.getElementById('loss_circumstances')) document.getElementById('loss_circumstances').value = '';
            if (document.getElementById('loss_report_no')) document.getElementById('loss_report_no').value = '';
            if (document.getElementById('loss_action_taken')) document.getElementById('loss_action_taken').value = '';
            if (document.getElementById('lost_by_name')) document.getElementById('lost_by_name').value = '';
            if (document.getElementById('lost_by_rank')) document.getElementById('lost_by_rank').value = '';
            if (document.getElementById('lost_by_nis')) document.getElementById('lost_by_nis').value = '';
            if (document.getElementById('lost_by_phone')) document.getElementById('lost_by_phone').value = '';
        } else if (selectedValue === 'Lost') {
            if (lostFields) lostFields.style.display = 'block';
            // Clear issued fields when not needed
            if (document.getElementById('custodian')) document.getElementById('custodian').value = '';
            if (document.getElementById('custodian_rank')) document.getElementById('custodian_rank').value = '';
            if (document.getElementById('custodian_nis')) document.getElementById('custodian_nis').value = '';
            if (document.getElementById('custodian_phone')) document.getElementById('custodian_phone').value = '';
        } else if (selectedValue === 'Other') {
            if (locationWrapper) locationWrapper.style.display = 'block';
        } else if (selectedValue === 'Armoury') {
            // Clear both issued and lost fields when in Armoury
            if (document.getElementById('custodian')) document.getElementById('custodian').value = '';
            if (document.getElementById('custodian_rank')) document.getElementById('custodian_rank').value = '';
            if (document.getElementById('custodian_nis')) document.getElementById('custodian_nis').value = '';
            if (document.getElementById('custodian_phone')) document.getElementById('custodian_phone').value = '';
            if (document.getElementById('loss_date')) document.getElementById('loss_date').value = '';
            if (document.getElementById('loss_circumstances')) document.getElementById('loss_circumstances').value = '';
            if (document.getElementById('loss_report_no')) document.getElementById('loss_report_no').value = '';
            if (document.getElementById('loss_action_taken')) document.getElementById('loss_action_taken').value = '';
            if (document.getElementById('lost_by_name')) document.getElementById('lost_by_name').value = '';
            if (document.getElementById('lost_by_rank')) document.getElementById('lost_by_rank').value = '';
            if (document.getElementById('lost_by_nis')) document.getElementById('lost_by_nis').value = '';
            if (document.getElementById('lost_by_phone')) document.getElementById('lost_by_phone').value = '';
        }
    }
    
    if (locationSelect) {
        locationSelect.addEventListener('change', toggleLocationFields);
        toggleLocationFields();
    }
    
    // Custodian Zone to Command dropdown
    const custodianZoneSelect = document.getElementById('custodian_zone_id');
    if (custodianZoneSelect) {
        custodianZoneSelect.addEventListener('change', function() {
            const zoneId = this.value;
            <?php if (!empty($old['custodian_command_id'])): ?>
            populateCommands(zoneId, 'custodian_command_id', <?php echo $old['custodian_command_id']; ?>);
            <?php else: ?>
            populateCommands(zoneId, 'custodian_command_id');
            <?php endif; ?>
        });
        
        <?php if (!empty($old['custodian_zone_id'])): ?>
        populateCommands('<?php echo $old['custodian_zone_id']; ?>', 'custodian_command_id', <?php echo json_encode($old['custodian_command_id'] ?? null); ?>);
        <?php endif; ?>
    }
    
    // Lost Zone to Command dropdown
    const lostZoneSelect = document.getElementById('lost_zone_id');
    if (lostZoneSelect) {
        lostZoneSelect.addEventListener('change', function() {
            const zoneId = this.value;
            <?php if (!empty($old['lost_command_id'])): ?>
            populateCommands(zoneId, 'lost_command_id', <?php echo $old['lost_command_id']; ?>);
            <?php else: ?>
            populateCommands(zoneId, 'lost_command_id');
            <?php endif; ?>
        });
        
        <?php if (!empty($old['lost_zone_id'])): ?>
        populateCommands('<?php echo $old['lost_zone_id']; ?>', 'lost_command_id', <?php echo json_encode($old['lost_command_id'] ?? null); ?>);
        <?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(baseUrl + '/api/validate_serial?type=weapon&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');
                        }
                    })
                    .catch(err => console.error('Validation error:', err));
            }, 500);
        });
    }
    
    // Auto-hide messages after 5 seconds
    const successAlert = document.getElementById('successAlert');
    if (successAlert) {
        setTimeout(function() {
            successAlert.style.display = 'none';
        }, 5000);
    }
    
    const errorAlert = document.getElementById('errorAlert');
    if (errorAlert) {
        setTimeout(function() {
            errorAlert.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('calibreOtherWrapper').style.display = 'none';
        document.getElementById('sourceOtherWrapper').style.display = 'none';
        document.getElementById('locationOtherWrapper').style.display = 'none';
        
        const issuedFields = document.getElementById('issuedFields');
        const lostFields = document.getElementById('lostFields');
        if (issuedFields) issuedFields.style.display = 'none';
        if (lostFields) lostFields.style.display = 'none';
        
        // Reset command dropdowns
        const custodianCommand = document.getElementById('custodian_command_id');
        if (custodianCommand) custodianCommand.innerHTML = '<option value="">Select Zone First</option>';
        
        const lostCommand = document.getElementById('lost_command_id');
        if (lostCommand) lostCommand.innerHTML = '<option value="">Select Zone First</option>';
        
        alert('Form has been reset');
    }
}
</script>