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

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

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-edit"></i>
                Edit Non-Lethal Weapon: <?php echo Security::escape($weapon['weapon_id']); ?>
            </h1>
            <p>Update non-lethal weapon information</p>
        </div>
        <div class="header-actions">
            <a href="<?php echo BASE_URL; ?>/non_lethal_weapons/show/<?php echo $weapon['id']; ?>" class="btn btn-info">
                <i class="fas fa-eye"></i> View Details
            </a>
            <a href="<?php echo BASE_URL; ?>/non_lethal_weapons" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Weapons
            </a>
        </div>
    </div>

    <!-- Form -->
    <div class="form-section">
        <form method="POST" action="<?php echo BASE_URL; ?>/non_lethal_weapons/update/<?php echo $weapon['id']; ?>" 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>Weapon ID</label>
                        <input type="text" value="<?php echo Security::escape($weapon['weapon_id']); ?>" 
                               class="form-control" readonly disabled>
                    </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($weapon['serial_no']); ?>" 
                               required maxlength="100" 
                               class="form-control <?php echo isset($errors['serial_no']) ? 'error' : ''; ?>">
                        <?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 $weapon['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($weapon['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($weapon['make_model']); ?>" 
                               required maxlength="255" 
                               class="form-control <?php echo isset($errors['make_model']) ? 'error' : ''; ?>">
                        <?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>
                            <?php foreach ($categories as $category): ?>
                            <option value="<?php echo $category['id']; ?>" 
                                    <?php echo ($weapon['category_id'] ?? '') == $category['id'] ? 'selected' : ''; ?>>
                                <?php echo Security::escape($category['category_name']); ?>
                            </option>
                            <?php endforeach; ?>
                            <option value="Other">Other (Specify)</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($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($weapon['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($weapon['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 ($weapon['power_source'] ?? '') == 'Battery' ? 'selected' : ''; ?>>Battery Operated</option>
                            <option value="Manual" <?php echo ($weapon['power_source'] ?? '') == 'Manual' ? 'selected' : ''; ?>>Manual/Mechanical</option>
                            <option value="Gas" <?php echo ($weapon['power_source'] ?? '') == 'Gas' ? 'selected' : ''; ?>>Gas Powered</option>
                            <option value="None" <?php echo ($weapon['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 ($weapon['less_lethal_rating'] ?? '') == 'Low' ? 'selected' : ''; ?>>Low - Minimal risk</option>
                            <option value="Medium" <?php echo ($weapon['less_lethal_rating'] ?? '') == 'Medium' ? 'selected' : ''; ?>>Medium - Moderate risk</option>
                            <option value="High" <?php echo ($weapon['less_lethal_rating'] ?? '') == 'High' ? 'selected' : ''; ?>>High - Significant risk</option>
                        </select>
                    </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 ($weapon['source'] ?? '') == 'FGN (NIS)' ? 'selected' : ''; ?>>FGN (NIS)</option>
                            <option value="Donor" <?php echo ($weapon['source'] ?? '') == 'Donor' ? 'selected' : ''; ?>>Donor</option>
                            <option value="Transfer" <?php echo ($weapon['source'] ?? '') == 'Transfer' ? 'selected' : ''; ?>>Transfer</option>
                            <option value="Recovered" <?php echo ($weapon['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($weapon['source_other'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>Date Acquired</label>
                        <input type="date" name="date_acquired" value="<?php echo Security::escape($weapon['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 ($weapon['condition'] ?? '') == 'Serviceable' ? 'selected' : ''; ?>>Serviceable</option>
                            <option value="Unserviceable" <?php echo ($weapon['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 ($weapon['current_location'] ?? '') == 'Armoury' ? 'selected' : ''; ?>>Armoury</option>
                            <option value="Issued" <?php echo ($weapon['current_location'] ?? '') == 'Issued' ? 'selected' : ''; ?>>Issued</option>
                            <option value="In Repair" <?php echo ($weapon['current_location'] ?? '') == 'In Repair' ? 'selected' : ''; ?>>In Repair</option>
                            <option value="Lost" <?php echo ($weapon['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 ($weapon['current_location'] ?? '') == 'Issued' ? '' : 'display: none;'; ?>">
                    <div class="form-group">
                        <label>Custodian Name</label>
                        <input type="text" name="custodian" value="<?php echo Security::escape($weapon['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($weapon['custodian_rank'] ?? ''); ?>" 
                               maxlength="50" class="form-control">
                    </div>
                </div>
                
                <div class="form-row" id="custodianNisField" style="<?php echo ($weapon['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($weapon['custodian_nis'] ?? ''); ?>" 
                               maxlength="50" class="form-control">
                    </div>
                </div>
                
                <div class="form-group" id="locationOtherWrapper" style="<?php echo ($weapon['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($weapon['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($weapon['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($weapon['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($weapon['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"><?php echo Security::escape($weapon['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> Update Non-Lethal Weapon
                </button>
                <a href="<?php echo BASE_URL; ?>/non_lethal_weapons/show/<?php echo $weapon['id']; ?>" class="btn btn-outline">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<script>
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;
            }
        });
        
        <?php if (!empty($weapon['weapon_type_other'])): ?>
        typeSelect.value = 'other';
        typeWrapper.style.display = 'block';
        <?php endif; ?>
    }
    
    // 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;
            }
        });
        
        <?php if (!empty($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;
            }
        });
        
        <?php if (!empty($weapon['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;
            }
        });
        
        <?php if (($weapon['current_location'] ?? '') == 'Issued'): ?>
        locationSelect.value = 'Issued';
        custodianFields.style.display = 'flex';
        custodianNisField.style.display = 'flex';
        <?php elseif (($weapon['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');
    const currentSerial = serialInput.value;
    let serialTimeout;
    
    if (serialInput) {
        serialInput.addEventListener('input', function() {
            clearTimeout(serialTimeout);
            const serial = this.value;
            
            if (serial === currentSerial || serial.length < 3) {
                serialValidation.innerHTML = '';
                return;
            }
            
            serialTimeout = setTimeout(() => {
                fetch('<?php echo BASE_URL; ?>/api/validate_serial?type=non_lethal&serial=' + encodeURIComponent(serial) + '&exclude_id=<?php echo $weapon['id']; ?>')
                    .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);
        });
    }
});
</script>

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