<?php
$title = 'Edit Weapon';
$active = '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 Weapon: <?php echo Security::escape($weapon['weapon_id']); ?>
            </h1>
            <p>Update weapon information</p>
        </div>
        <div class="header-actions">
            <a href="<?php echo BASE_URL; ?>/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; ?>/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; ?>/weapons/update/<?php echo $weapon['id']; ?>" id="weaponForm">
            <?php echo Security::csrfField(); ?>
            
            <!-- Hidden field for weapon ID to ensure it's submitted -->
            <input type="hidden" name="weapon_record_id" value="<?php echo $weapon['id']; ?>">
            
            <!-- 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" value="<?php echo Security::escape($weapon['weapon_id']); ?>" 
                               required maxlength="50"
                               class="form-control <?php echo isset($errors['weapon_id']) ? 'error' : ''; ?>">
                        <?php if (isset($errors['weapon_id'])): ?>
                            <small class="error-text"><?php echo $errors['weapon_id']; ?></small>
                        <?php endif; ?>
                    </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" <?php echo (!empty($weapon['weapon_type_other']) && $weapon['weapon_type_id'] == '') ? 'selected' : ''; ?>>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>
            
            <!-- Calibre Information -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-bullseye"></i> Calibre Information</h3>
                </div>
                
                <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 ($weapon['calibre_id'] == $calibre['id']) ? 'selected' : ''; ?>>
                                <?php echo Security::escape($calibre['calibre_name']); ?>
                            </option>
                            <?php endforeach; ?>
                            <option value="other" <?php echo (!empty($weapon['calibre_other']) && $weapon['calibre_id'] == '') ? 'selected' : ''; ?>>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($weapon['calibre_other'] ?? ''); ?>">
                    </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 Purchase" <?php echo ($weapon['source'] == 'FGN Purchase') ? 'selected' : ''; ?>>FGN Purchase</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" <?php echo (!empty($weapon['source_other']) && !in_array($weapon['source'], ['FGN Purchase', 'Donor', 'Transfer', 'Recovered'])) ? 'selected' : ''; ?>>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>
                            <option value="Under Repair" <?php echo ($weapon['condition'] == 'Under Repair') ? 'selected' : ''; ?>>Under Repair</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>
                            <option value="Other" <?php echo (!empty($weapon['current_location_other']) && !in_array($weapon['current_location'], ['Armoury', 'Issued', 'In Repair', 'Lost'])) ? 'selected' : ''; ?>>Other</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: flex;' : '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: flex;' : '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 (!empty($weapon['current_location_other']) && !in_array($weapon['current_location'], ['Armoury', 'Issued', 'In Repair', 'Lost'])) ? '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($weapon['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($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>
            
            <!-- 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 Weapon
                </button>
                <a href="<?php echo BASE_URL; ?>/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';
                if (typeOther) typeOther.required = true;
            } else {
                typeWrapper.style.display = 'none';
                if (typeOther) typeOther.required = false;
            }
        });
        
        <?php if (!empty($weapon['weapon_type_other']) && empty($weapon['weapon_type_id'])): ?>
        // Already handled by the selected attribute
        <?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';
                if (calibreOther) calibreOther.required = true;
            } else {
                calibreWrapper.style.display = 'none';
                if (calibreOther) calibreOther.required = false;
            }
        });
        
        <?php if (!empty($weapon['calibre_other']) && empty($weapon['calibre_id'])): ?>
        // Already handled by the selected attribute
        <?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';
                if (sourceOther) sourceOther.required = true;
            } else {
                sourceWrapper.style.display = 'none';
                if (sourceOther) sourceOther.required = false;
            }
        });
        
        <?php if (!empty($weapon['source_other']) && !in_array($weapon['source'], ['FGN Purchase', 'Donor', 'Transfer', 'Recovered'])): ?>
        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') {
                if (custodianFields) custodianFields.style.display = 'flex';
                if (custodianNisField) custodianNisField.style.display = 'flex';
            } else {
                if (custodianFields) custodianFields.style.display = 'none';
                if (custodianNisField) custodianNisField.style.display = 'none';
            }
            
            if (this.value === 'Other') {
                if (locationWrapper) locationWrapper.style.display = 'block';
                if (locationOther) locationOther.required = true;
            } else {
                if (locationWrapper) locationWrapper.style.display = 'none';
                if (locationOther) locationOther.required = false;
            }
        });
    }
    
    // Serial number validation
    const serialInput = document.getElementById('serial_no');
    const serialValidation = document.getElementById('serialValidation');
    const currentSerial = serialInput ? serialInput.value : '';
    let serialTimeout;
    
    if (serialInput) {
        serialInput.addEventListener('input', function() {
            clearTimeout(serialTimeout);
            const serial = this.value;
            
            if (serial === currentSerial || serial.length < 3) {
                if (serialValidation) serialValidation.innerHTML = '';
                return;
            }
            
            serialTimeout = setTimeout(() => {
                fetch('<?php echo BASE_URL; ?>/api/validate_serial?type=weapon&serial=' + encodeURIComponent(serial) + '&exclude_id=<?php echo $weapon['id']; ?>')
                    .then(response => response.json())
                    .then(data => {
                        if (serialValidation) {
                            if (data.exists) {
                                serialValidation.innerHTML = '<span class="text-danger"><i class="fas fa-times-circle"></i> Serial number already exists</span>';
                                if (serialInput) serialInput.classList.add('error');
                            } else {
                                serialValidation.innerHTML = '<span class="text-success"><i class="fas fa-check-circle"></i> Serial number available</span>';
                                if (serialInput) serialInput.classList.remove('error');
                            }
                        }
                    })
                    .catch(error => {
                        console.error('Error validating serial:', error);
                    });
            }, 500);
        });
    }
});
</script>