<?php
/**
 * Non-Lethal Weapons Management Controller
 */
class NonLethalWeaponsController extends Controller {
    
    public function index() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.view')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to view non-lethal weapons']);
            return;
        }
        
        $weapons = Database::fetchAll(
            "SELECT nw.*, 
                    nwt.type_name as weapon_type_name,
                    nwc.category_name as category_name
             FROM non_lethal_weapons_inventory nw
             LEFT JOIN non_lethal_weapon_types nwt ON nw.weapon_type_id = nwt.id
             LEFT JOIN non_lethal_categories nwc ON nw.category_id = nwc.id
             ORDER BY nw.created_at DESC"
        );
        
        if ($weapons === false) $weapons = [];
        
        // Calculate statistics
        $statistics = [
            'total' => count($weapons),
            'issued' => 0,
            'serviceable' => 0,
            'unserviceable' => 0,
            'expired' => 0,
            'damaged' => 0
        ];
        
        $today = date('Y-m-d');
        
        foreach ($weapons as $weapon) {
            if (($weapon['current_location'] ?? '') == 'Issued') {
                $statistics['issued']++;
            }
            if (($weapon['condition'] ?? '') == 'Serviceable') {
                $statistics['serviceable']++;
            } elseif (($weapon['condition'] ?? '') == 'Unserviceable') {
                $statistics['unserviceable']++;
            }
            
            // Check for expired chemical agents
            if (!empty($weapon['expiry_date']) && $weapon['expiry_date'] < $today) {
                $statistics['expired']++;
            }
            
            if (($weapon['status'] ?? '') == 'Damaged') {
                $statistics['damaged']++;
            }
        }
        
        // Get filter options
        $weaponTypes = Database::fetchAll("SELECT id, type_name FROM non_lethal_weapon_types ORDER BY type_name");
        if ($weaponTypes === false) $weaponTypes = [];
        
        $categories = Database::fetchAll("SELECT id, category_name FROM non_lethal_categories ORDER BY category_name");
        if ($categories === false) $categories = [];
        
        $this->view('non_lethal_weapons/index', [
            'weapons' => $weapons,
            'statistics' => $statistics,
            'weaponTypes' => $weaponTypes,
            'categories' => $categories
        ]);
    }
    
    public function create() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.create')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to create non-lethal weapons']);
            return;
        }
        
        $weaponTypes = Database::fetchAll("SELECT * FROM non_lethal_weapon_types ORDER BY type_name");
        $categories = Database::fetchAll("SELECT * FROM non_lethal_categories ORDER BY category_name");
        
        if ($weaponTypes === false) $weaponTypes = [];
        if ($categories === false) $categories = [];
        
        $this->view('non_lethal_weapons/create', [
            'weaponTypes' => $weaponTypes,
            'categories' => $categories
        ]);
    }
    
    public function store() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.create')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to create non-lethal weapons']);
            return;
        }
        
        if (!Security::validateCsrfToken($_POST['csrf_token'] ?? '')) {
            $this->redirect('non_lethal_weapons/create', ['error' => 'Invalid security token']);
            return;
        }
        
        // Manual validation
        $errors = [];
        
        if (empty($_POST['weapon_id'])) {
            $errors['weapon_id'] = 'Weapon ID is required';
        }
        
        if (empty($_POST['make_model'])) {
            $errors['make_model'] = 'Make/Model is required';
        } elseif (strlen($_POST['make_model']) > 255) {
            $errors['make_model'] = 'Make/Model must not exceed 255 characters';
        }
        
        if (empty($_POST['serial_no'])) {
            $errors['serial_no'] = 'Serial number is required';
        }
        
        if (empty($_POST['source'])) {
            $errors['source'] = 'Source is required';
        }
        
        if (empty($_POST['condition'])) {
            $errors['condition'] = 'Condition is required';
        }
        
        if (empty($_POST['current_location'])) {
            $errors['current_location'] = 'Current location is required';
        }
        
        if (empty($_POST['weapon_category'])) {
            $errors['weapon_category'] = 'Weapon category is required';
        }
        
        // Check for duplicate weapon_id
        if (!empty($_POST['weapon_id'])) {
            $existing = Database::fetchOne(
                "SELECT id FROM non_lethal_weapons_inventory WHERE weapon_id = ?",
                [$_POST['weapon_id']]
            );
            if ($existing) {
                $errors['weapon_id'] = 'Weapon ID already exists';
            }
        }
        
        // Check for duplicate serial_no
        if (!empty($_POST['serial_no'])) {
            $existing = Database::fetchOne(
                "SELECT id FROM non_lethal_weapons_inventory WHERE serial_no = ?",
                [$_POST['serial_no']]
            );
            if ($existing) {
                $errors['serial_no'] = 'Serial number already exists';
            }
        }
        
        if (!empty($errors)) {
            Session::set('errors', $errors);
            Session::set('old', $_POST);
            $this->redirect('non_lethal_weapons/create');
            return;
        }
        
        Database::beginTransaction();
        
        try {
            // Handle category
            $categoryId = null;
            if (!empty($_POST['weapon_category']) && $_POST['weapon_category'] !== 'Other') {
                // Check if it's an existing category ID or needs to be looked up
                if (is_numeric($_POST['weapon_category'])) {
                    $categoryId = $_POST['weapon_category'];
                } else {
                    $category = Database::fetchOne(
                        "SELECT id FROM non_lethal_categories WHERE category_name = ?",
                        [$_POST['weapon_category']]
                    );
                    if ($category) {
                        $categoryId = $category['id'];
                    }
                }
            }
            
            $weaponId = Database::insert('non_lethal_weapons_inventory', [
                'weapon_id' => $_POST['weapon_id'],
                'weapon_type_id' => !empty($_POST['weapon_type_id']) && $_POST['weapon_type_id'] !== 'other' ? $_POST['weapon_type_id'] : null,
                'weapon_type_other' => ($_POST['weapon_type_id'] ?? '') === 'other' ? ($_POST['weapon_type_other'] ?? null) : null,
                'category_id' => $categoryId,
                'category_other' => ($_POST['weapon_category'] ?? '') === 'Other' ? ($_POST['weapon_category_other'] ?? null) : null,
                'make_model' => $_POST['make_model'],
                'serial_no' => $_POST['serial_no'],
                'ammunition_type' => $_POST['ammunition_type'] ?? null,
                'effective_range' => !empty($_POST['effective_range']) ? $_POST['effective_range'] : null,
                'power_source' => $_POST['power_source'] ?? null,
                'less_lethal_rating' => $_POST['less_lethal_rating'] ?? 'Medium',
                'expiry_date' => !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null,
                'source' => $_POST['source'] === 'Other' ? ($_POST['source_other'] ?? 'Other') : $_POST['source'],
                'condition' => $_POST['condition'],
                'current_location' => $_POST['current_location'] === 'Other' ? ($_POST['current_location_other'] ?? 'Other') : $_POST['current_location'],
                'current_location_other' => $_POST['current_location'] === 'Other' ? ($_POST['current_location_other'] ?? null) : null,
                'custodian' => ($_POST['current_location'] ?? '') === 'Issued' ? ($_POST['custodian'] ?? null) : null,
                'custodian_rank' => ($_POST['current_location'] ?? '') === 'Issued' ? ($_POST['custodian_rank'] ?? null) : null,
                'custodian_nis' => ($_POST['current_location'] ?? '') === 'Issued' ? ($_POST['custodian_nis'] ?? null) : null,
                'date_acquired' => !empty($_POST['date_acquired']) ? $_POST['date_acquired'] : null,
                'last_inspection_date' => !empty($_POST['last_inspection_date']) ? $_POST['last_inspection_date'] : null,
                'next_inspection_date' => !empty($_POST['next_inspection_date']) ? $_POST['next_inspection_date'] : null,
                'remarks' => $_POST['remarks'] ?? null,
                'status' => 'Active',
                'created_by' => Auth::id()
            ]);
            
            if (!$weaponId) {
                throw new Exception("Failed to insert non-lethal weapon record");
            }
            
            Database::commit();
            
            AuditLogger::logCreate('non_lethal_weapons_inventory', $weaponId, $_POST);
            
            $this->redirect('non_lethal_weapons', ['success' => 'Non-lethal weapon added successfully']);
            
        } catch (Exception $e) {
            Database::rollBack();
            error_log("Non-lethal weapon creation error: " . $e->getMessage());
            $this->redirect('non_lethal_weapons/create', ['error' => 'Failed to add non-lethal weapon: ' . $e->getMessage()]);
        }
    }
    
    public function show($id) {
        // Check permission
        if (!Auth::can('non_lethal_weapons.view')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to view non-lethal weapons']);
            return;
        }
        
        $weapon = Database::fetchOne(
            "SELECT nw.*, 
                    nwt.type_name as weapon_type_name,
                    nwc.category_name as category_name,
                    u.full_name as created_by_name
             FROM non_lethal_weapons_inventory nw
             LEFT JOIN non_lethal_weapon_types nwt ON nw.weapon_type_id = nwt.id
             LEFT JOIN non_lethal_categories nwc ON nw.category_id = nwc.id
             LEFT JOIN users u ON nw.created_by = u.id
             WHERE nw.id = ?",
            [$id]
        );
        
        if (!$weapon) {
            $this->redirect('non_lethal_weapons', ['error' => 'Non-lethal weapon not found']);
            return;
        }
        
        // Get issue history
        $issueHistory = Database::fetchAll(
            "SELECT nwil.*, 
                    CONCAT(nwil.officer_name, ' (', nwil.officer_rank, ')') as officer,
                    req.requisition_number
             FROM non_lethal_weapon_issue_log nwil
             LEFT JOIN requisitions req ON nwil.requisition_id = req.id
             WHERE nwil.weapon_id = ? 
             ORDER BY nwil.issue_date DESC",
            [$id]
        );
        if ($issueHistory === false) $issueHistory = [];
        
        // Get maintenance history
        $maintenanceHistory = Database::fetchAll(
            "SELECT * FROM non_lethal_weapon_maintenance_log
             WHERE weapon_id = ?
             ORDER BY maintenance_date DESC",
            [$id]
        );
        if ($maintenanceHistory === false) $maintenanceHistory = [];
        
        AuditLogger::logView('non_lethal_weapons_inventory', $id);
        
        $this->view('non_lethal_weapons/show', [
            'weapon' => $weapon,
            'issueHistory' => $issueHistory,
            'maintenanceHistory' => $maintenanceHistory
        ]);
    }
    
    public function edit($id) {
        // Check permission
        if (!Auth::can('non_lethal_weapons.edit')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to edit non-lethal weapons']);
            return;
        }
        
        $weapon = Database::fetchOne("SELECT * FROM non_lethal_weapons_inventory WHERE id = ?", [$id]);
        
        if (!$weapon) {
            $this->redirect('non_lethal_weapons', ['error' => 'Non-lethal weapon not found']);
            return;
        }
        
        $weaponTypes = Database::fetchAll("SELECT * FROM non_lethal_weapon_types ORDER BY type_name");
        $categories = Database::fetchAll("SELECT * FROM non_lethal_categories ORDER BY category_name");
        
        if ($weaponTypes === false) $weaponTypes = [];
        if ($categories === false) $categories = [];
        
        $this->view('non_lethal_weapons/edit', [
            'weapon' => $weapon,
            'weaponTypes' => $weaponTypes,
            'categories' => $categories
        ]);
    }
    
    public function update($id) {
        // Check permission
        if (!Auth::can('non_lethal_weapons.edit')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to edit non-lethal weapons']);
            return;
        }
        
        if (!Security::validateCsrfToken($_POST['csrf_token'] ?? '')) {
            $this->redirect("non_lethal_weapons/edit/$id", ['error' => 'Invalid security token']);
            return;
        }
        
        $oldData = Database::fetchOne("SELECT * FROM non_lethal_weapons_inventory WHERE id = ?", [$id]);
        
        if (!$oldData) {
            $this->redirect('non_lethal_weapons', ['error' => 'Non-lethal weapon not found']);
            return;
        }
        
        // Manual validation
        $errors = [];
        
        if (empty($_POST['weapon_id'])) {
            $errors['weapon_id'] = 'Weapon ID is required';
        }
        
        if (empty($_POST['make_model'])) {
            $errors['make_model'] = 'Make/Model is required';
        } elseif (strlen($_POST['make_model']) > 255) {
            $errors['make_model'] = 'Make/Model must not exceed 255 characters';
        }
        
        if (empty($_POST['serial_no'])) {
            $errors['serial_no'] = 'Serial number is required';
        }
        
        if (empty($_POST['source'])) {
            $errors['source'] = 'Source is required';
        }
        
        if (empty($_POST['condition'])) {
            $errors['condition'] = 'Condition is required';
        }
        
        if (empty($_POST['current_location'])) {
            $errors['current_location'] = 'Current location is required';
        }
        
        // Check for duplicate weapon_id (excluding current)
        if (!empty($_POST['weapon_id']) && $_POST['weapon_id'] !== $oldData['weapon_id']) {
            $existing = Database::fetchOne(
                "SELECT id FROM non_lethal_weapons_inventory WHERE weapon_id = ? AND id != ?",
                [$_POST['weapon_id'], $id]
            );
            if ($existing) {
                $errors['weapon_id'] = 'Weapon ID already exists';
            }
        }
        
        // Check for duplicate serial_no (excluding current)
        if (!empty($_POST['serial_no']) && $_POST['serial_no'] !== $oldData['serial_no']) {
            $existing = Database::fetchOne(
                "SELECT id FROM non_lethal_weapons_inventory WHERE serial_no = ? AND id != ?",
                [$_POST['serial_no'], $id]
            );
            if ($existing) {
                $errors['serial_no'] = 'Serial number already exists';
            }
        }
        
        if (!empty($errors)) {
            Session::set('errors', $errors);
            $this->redirect("non_lethal_weapons/edit/$id");
            return;
        }
        
        Database::beginTransaction();
        
        try {
            // Handle category
            $categoryId = $oldData['category_id'];
            if (!empty($_POST['weapon_category']) && $_POST['weapon_category'] !== 'Other') {
                if (is_numeric($_POST['weapon_category'])) {
                    $categoryId = $_POST['weapon_category'];
                } else {
                    $category = Database::fetchOne(
                        "SELECT id FROM non_lethal_categories WHERE category_name = ?",
                        [$_POST['weapon_category']]
                    );
                    if ($category) {
                        $categoryId = $category['id'];
                    }
                }
            } elseif (($_POST['weapon_category'] ?? '') === 'Other') {
                $categoryId = null;
            }
            
            Database::update('non_lethal_weapons_inventory', [
                'weapon_id' => $_POST['weapon_id'],
                'weapon_type_id' => !empty($_POST['weapon_type_id']) && $_POST['weapon_type_id'] !== 'other' ? $_POST['weapon_type_id'] : null,
                'weapon_type_other' => ($_POST['weapon_type_id'] ?? '') === 'other' ? ($_POST['weapon_type_other'] ?? null) : null,
                'category_id' => $categoryId,
                'category_other' => ($_POST['weapon_category'] ?? '') === 'Other' ? ($_POST['weapon_category_other'] ?? null) : null,
                'make_model' => $_POST['make_model'],
                'serial_no' => $_POST['serial_no'],
                'ammunition_type' => $_POST['ammunition_type'] ?? null,
                'effective_range' => !empty($_POST['effective_range']) ? $_POST['effective_range'] : null,
                'power_source' => $_POST['power_source'] ?? null,
                'less_lethal_rating' => $_POST['less_lethal_rating'] ?? 'Medium',
                'expiry_date' => !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null,
                'source' => $_POST['source'] === 'Other' ? ($_POST['source_other'] ?? 'Other') : $_POST['source'],
                'condition' => $_POST['condition'],
                'current_location' => $_POST['current_location'] === 'Other' ? ($_POST['current_location_other'] ?? 'Other') : $_POST['current_location'],
                'current_location_other' => $_POST['current_location'] === 'Other' ? ($_POST['current_location_other'] ?? null) : null,
                'custodian' => ($_POST['current_location'] ?? '') === 'Issued' ? ($_POST['custodian'] ?? null) : null,
                'custodian_rank' => ($_POST['current_location'] ?? '') === 'Issued' ? ($_POST['custodian_rank'] ?? null) : null,
                'custodian_nis' => ($_POST['current_location'] ?? '') === 'Issued' ? ($_POST['custodian_nis'] ?? null) : null,
                'date_acquired' => !empty($_POST['date_acquired']) ? $_POST['date_acquired'] : null,
                'last_inspection_date' => !empty($_POST['last_inspection_date']) ? $_POST['last_inspection_date'] : null,
                'next_inspection_date' => !empty($_POST['next_inspection_date']) ? $_POST['next_inspection_date'] : null,
                'remarks' => $_POST['remarks'] ?? null,
                'status' => $_POST['status'] ?? 'Active'
            ], 'id = ?', [$id]);
            
            Database::commit();
            
            AuditLogger::logUpdate('non_lethal_weapons_inventory', $id, $oldData, $_POST);
            
            $this->redirect("non_lethal_weapons/show/$id", ['success' => 'Non-lethal weapon updated successfully']);
            
        } catch (Exception $e) {
            Database::rollBack();
            error_log("Non-lethal weapon update error: " . $e->getMessage());
            $this->redirect("non_lethal_weapons/edit/$id", ['error' => 'Failed to update non-lethal weapon: ' . $e->getMessage()]);
        }
    }
    
    public function delete($id) {
        // Check permission
        if (!Auth::can('non_lethal_weapons.delete')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to delete non-lethal weapons']);
            return;
        }
        
        $weapon = Database::fetchOne("SELECT * FROM non_lethal_weapons_inventory WHERE id = ?", [$id]);
        
        if (!$weapon) {
            $this->redirect('non_lethal_weapons', ['error' => 'Non-lethal weapon not found']);
            return;
        }
        
        // Check if weapon has issue history
        $issueCount = Database::fetchOne(
            "SELECT COUNT(*) as count FROM non_lethal_weapon_issue_log WHERE weapon_id = ?",
            [$id]
        )['count'] ?? 0;
        
        if ($issueCount > 0) {
            $this->redirect('non_lethal_weapons', ['error' => 'Cannot delete non-lethal weapon with issue history. Consider marking as decommissioned instead.']);
            return;
        }
        
        Database::beginTransaction();
        
        try {
            Database::delete('non_lethal_weapons_inventory', 'id = ?', [$id]);
            
            Database::commit();
            
            AuditLogger::logDelete('non_lethal_weapons_inventory', $id, $weapon);
            
            $this->redirect('non_lethal_weapons', ['success' => 'Non-lethal weapon deleted successfully']);
            
        } catch (Exception $e) {
            Database::rollBack();
            error_log("Non-lethal weapon deletion error: " . $e->getMessage());
            $this->redirect('non_lethal_weapons', ['error' => 'Failed to delete non-lethal weapon: ' . $e->getMessage()]);
        }
    }
    
    public function dashboard() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.view')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to view non-lethal weapons dashboard']);
            return;
        }
        
        $today = date('Y-m-d');
        
        $stats = [
            'total' => Database::fetchOne("SELECT COUNT(*) as count FROM non_lethal_weapons_inventory")['count'] ?? 0,
            'issued' => Database::fetchOne("SELECT COUNT(*) as count FROM non_lethal_weapons_inventory WHERE current_location = 'Issued'")['count'] ?? 0,
            'serviceable' => Database::fetchOne("SELECT COUNT(*) as count FROM non_lethal_weapons_inventory WHERE `condition` = 'Serviceable'")['count'] ?? 0,
            'unserviceable' => Database::fetchOne("SELECT COUNT(*) as count FROM non_lethal_weapons_inventory WHERE `condition` = 'Unserviceable'")['count'] ?? 0,
            'in_repair' => Database::fetchOne("SELECT COUNT(*) as count FROM non_lethal_weapons_inventory WHERE current_location = 'In Repair'")['count'] ?? 0,
            'expired' => Database::fetchOne("SELECT COUNT(*) as count FROM non_lethal_weapons_inventory WHERE expiry_date IS NOT NULL AND expiry_date < ?", [$today])['count'] ?? 0,
            'new_this_month' => Database::fetchOne(
                "SELECT COUNT(*) as count FROM non_lethal_weapons_inventory WHERE MONTH(created_at) = MONTH(CURRENT_DATE()) AND YEAR(created_at) = YEAR(CURRENT_DATE())"
            )['count'] ?? 0,
            'units_count' => Database::fetchOne("SELECT COUNT(DISTINCT unit) as count FROM non_lethal_weapon_issue_log WHERE unit IS NOT NULL")['count'] ?? 0,
            'last_audit' => Database::fetchOne("SELECT MAX(last_inspection_date) as last_audit FROM non_lethal_weapons_inventory")['last_audit'] ?? 'N/A'
        ];
        
        // Weapons by type
        $byType = Database::fetchAll(
            "SELECT COALESCE(nwt.type_name, nw.weapon_type_other, 'Other') as type, COUNT(*) as count 
             FROM non_lethal_weapons_inventory nw
             LEFT JOIN non_lethal_weapon_types nwt ON nw.weapon_type_id = nwt.id
             GROUP BY COALESCE(nwt.type_name, nw.weapon_type_other, 'Other')
             ORDER BY count DESC"
        );
        if ($byType === false) $byType = [];
        
        $stats['by_type'] = [];
        foreach ($byType as $item) {
            $stats['by_type'][$item['type']] = $item['count'];
        }
        
        // Weapons by calibre (category in this context)
        $byCategory = Database::fetchAll(
            "SELECT COALESCE(nwc.category_name, nw.category_other, 'Other') as category, COUNT(*) as count 
             FROM non_lethal_weapons_inventory nw
             LEFT JOIN non_lethal_categories nwc ON nw.category_id = nwc.id
             GROUP BY COALESCE(nwc.category_name, nw.category_other, 'Other')
             ORDER BY count DESC"
        );
        if ($byCategory === false) $byCategory = [];
        
        $stats['by_calibre'] = [];
        foreach ($byCategory as $item) {
            $stats['by_calibre'][$item['category']] = $item['count'];
        }
        
        // Recent issues
        $recentIssues = Database::fetchAll(
            "SELECT nwil.*, nw.make_model, nw.weapon_id as weapon_code
             FROM non_lethal_weapon_issue_log nwil
             JOIN non_lethal_weapons_inventory nw ON nwil.weapon_id = nw.id
             ORDER BY nwil.issue_date DESC
             LIMIT 10"
        );
        if ($recentIssues === false) $recentIssues = [];
        
        $this->view('non_lethal_weapons/dashboard', [
            'stats' => $stats,
            'recentIssues' => $recentIssues
        ]);
    }
    
    public function types() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.create')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to manage non-lethal weapon types']);
            return;
        }
        
        $types = Database::fetchAll("SELECT * FROM non_lethal_weapon_types ORDER BY type_name");
        if ($types === false) $types = [];
        
        $this->view('non_lethal_weapons/types', ['types' => $types]);
    }
    
    public function storeType() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.create')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to manage non-lethal weapon types']);
            return;
        }
        
        if (!Security::validateCsrfToken($_POST['csrf_token'] ?? '')) {
            $this->redirect('non_lethal_weapons/types', ['error' => 'Invalid security token']);
            return;
        }
        
        $errors = [];
        
        if (empty($_POST['type_name'])) {
            $errors['type_name'] = 'Type name is required';
        }
        
        if (!empty($_POST['type_name'])) {
            $existing = Database::fetchOne(
                "SELECT id FROM non_lethal_weapon_types WHERE type_name = ?",
                [$_POST['type_name']]
            );
            if ($existing) {
                $errors['type_name'] = 'Weapon type already exists';
            }
        }
        
        if (!empty($errors)) {
            Session::set('errors', $errors);
            $this->redirect('non_lethal_weapons/types');
            return;
        }
        
        try {
            Database::insert('non_lethal_weapon_types', [
                'type_name' => $_POST['type_name'],
                'category' => $_POST['category'] ?? null,
                'description' => $_POST['description'] ?? null,
                'default_less_lethal_rating' => $_POST['default_less_lethal_rating'] ?? 'Medium'
            ]);
            
            $this->redirect('non_lethal_weapons/types', ['success' => 'Non-lethal weapon type added successfully']);
            
        } catch (Exception $e) {
            error_log("Non-lethal weapon type creation error: " . $e->getMessage());
            $this->redirect('non_lethal_weapons/types', ['error' => 'Failed to add weapon type']);
        }
    }
    
    public function deleteType($id) {
        // Check permission
        if (!Auth::can('non_lethal_weapons.delete')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to delete non-lethal weapon types']);
            return;
        }
        
        $type = Database::fetchOne("SELECT * FROM non_lethal_weapon_types WHERE id = ?", [$id]);
        
        if (!$type) {
            $this->redirect('non_lethal_weapons/types', ['error' => 'Weapon type not found']);
            return;
        }
        
        $inUse = Database::fetchOne(
            "SELECT COUNT(*) as count FROM non_lethal_weapons_inventory WHERE weapon_type_id = ?",
            [$id]
        )['count'] ?? 0;
        
        if ($inUse > 0) {
            $this->redirect('non_lethal_weapons/types', ['error' => 'Cannot delete weapon type that is in use']);
            return;
        }
        
        try {
            Database::delete('non_lethal_weapon_types', 'id = ?', [$id]);
            $this->redirect('non_lethal_weapons/types', ['success' => 'Weapon type deleted successfully']);
        } catch (Exception $e) {
            error_log("Non-lethal weapon type deletion error: " . $e->getMessage());
            $this->redirect('non_lethal_weapons/types', ['error' => 'Failed to delete weapon type']);
        }
    }
    
    public function categories() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.create')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to manage categories']);
            return;
        }
        
        $categories = Database::fetchAll("SELECT * FROM non_lethal_categories ORDER BY category_name");
        if ($categories === false) $categories = [];
        
        $this->view('non_lethal_weapons/categories', ['categories' => $categories]);
    }
    
    public function storeCategory() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.create')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to manage categories']);
            return;
        }
        
        if (!Security::validateCsrfToken($_POST['csrf_token'] ?? '')) {
            $this->redirect('non_lethal_weapons/categories', ['error' => 'Invalid security token']);
            return;
        }
        
        $errors = [];
        
        if (empty($_POST['category_name'])) {
            $errors['category_name'] = 'Category name is required';
        }
        
        if (!empty($_POST['category_name'])) {
            $existing = Database::fetchOne(
                "SELECT id FROM non_lethal_categories WHERE category_name = ?",
                [$_POST['category_name']]
            );
            if ($existing) {
                $errors['category_name'] = 'Category already exists';
            }
        }
        
        if (!empty($errors)) {
            Session::set('errors', $errors);
            $this->redirect('non_lethal_weapons/categories');
            return;
        }
        
        try {
            Database::insert('non_lethal_categories', [
                'category_name' => $_POST['category_name'],
                'description' => $_POST['description'] ?? null,
                'risk_level' => $_POST['risk_level'] ?? 'Medium',
                'requires_training' => isset($_POST['requires_training']) ? 1 : 0
            ]);
            
            $this->redirect('non_lethal_weapons/categories', ['success' => 'Category added successfully']);
            
        } catch (Exception $e) {
            error_log("Category creation error: " . $e->getMessage());
            $this->redirect('non_lethal_weapons/categories', ['error' => 'Failed to add category']);
        }
    }
    
    public function deleteCategory($id) {
        // Check permission
        if (!Auth::can('non_lethal_weapons.delete')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to delete categories']);
            return;
        }
        
        $category = Database::fetchOne("SELECT * FROM non_lethal_categories WHERE id = ?", [$id]);
        
        if (!$category) {
            $this->redirect('non_lethal_weapons/categories', ['error' => 'Category not found']);
            return;
        }
        
        $inUse = Database::fetchOne(
            "SELECT COUNT(*) as count FROM non_lethal_weapons_inventory WHERE category_id = ?",
            [$id]
        )['count'] ?? 0;
        
        if ($inUse > 0) {
            $this->redirect('non_lethal_weapons/categories', ['error' => 'Cannot delete category that is in use']);
            return;
        }
        
        try {
            Database::delete('non_lethal_categories', 'id = ?', [$id]);
            $this->redirect('non_lethal_weapons/categories', ['success' => 'Category deleted successfully']);
        } catch (Exception $e) {
            error_log("Category deletion error: " . $e->getMessage());
            $this->redirect('non_lethal_weapons/categories', ['error' => 'Failed to delete category']);
        }
    }
    
    public function issueLog() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.view')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to view issue logs']);
            return;
        }
        
        $issues = Database::fetchAll(
            "SELECT nwil.*, nw.weapon_id as weapon_code, nw.make_model
             FROM non_lethal_weapon_issue_log nwil
             JOIN non_lethal_weapons_inventory nw ON nwil.weapon_id = nw.id
             LEFT JOIN requisitions req ON nwil.requisition_id = req.id
             ORDER BY nwil.issue_date DESC
             LIMIT 100"
        );
        
        if ($issues === false) $issues = [];
        
        $this->view('non_lethal_weapons/issue_log', ['issues' => $issues]);
    }
    
    public function createIssue() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.edit')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to issue non-lethal weapons']);
            return;
        }
        
        $weapons = Database::fetchAll(
            "SELECT nw.*, nwt.type_name, nwc.category_name
             FROM non_lethal_weapons_inventory nw
             LEFT JOIN non_lethal_weapon_types nwt ON nw.weapon_type_id = nwt.id
             LEFT JOIN non_lethal_categories nwc ON nw.category_id = nwc.id
             WHERE nw.current_location != 'Issued' 
               AND nw.current_location != 'Lost'
               AND nw.condition = 'Serviceable'
               AND (nw.expiry_date IS NULL OR nw.expiry_date > CURDATE())
             ORDER BY nw.weapon_id"
        );
        
        if ($weapons === false) $weapons = [];
        
        $this->view('non_lethal_weapons/issue_create', ['weapons' => $weapons]);
    }
    
    public function storeIssue() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.edit')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to issue non-lethal weapons']);
            return;
        }
        
        if (!Security::validateCsrfToken($_POST['csrf_token'] ?? '')) {
            $this->redirect('non_lethal_weapons/issue', ['error' => 'Invalid security token']);
            return;
        }
        
        $errors = [];
        
        if (empty($_POST['weapon_id'])) {
            $errors['weapon_id'] = 'Weapon is required';
        }
        
        if (empty($_POST['officer_name'])) {
            $errors['officer_name'] = 'Officer name is required';
        }
        
        if (empty($_POST['officer_rank'])) {
            $errors['officer_rank'] = 'Officer rank is required';
        }
        
        if (empty($_POST['unit'])) {
            $errors['unit'] = 'Unit is required';
        }
        
        if (empty($_POST['purpose'])) {
            $errors['purpose'] = 'Purpose is required';
        }
        
        if (empty($_POST['approved_by'])) {
            $errors['approved_by'] = 'Approving officer is required';
        }
        
        if (!empty($errors)) {
            Session::set('errors', $errors);
            Session::set('old', $_POST);
            $this->redirect('non_lethal_weapons/issue');
            return;
        }
        
        Database::beginTransaction();
        
        try {
            $issueId = Database::insert('non_lethal_weapon_issue_log', [
                'weapon_id' => $_POST['weapon_id'],
                'requisition_id' => $_POST['requisition_id'] ?? null,
                'issue_date' => $_POST['issue_date'] ?? date('Y-m-d'),
                'officer_name' => $_POST['officer_name'],
                'officer_rank' => $_POST['officer_rank'],
                'officer_nis' => $_POST['officer_nis'] ?? null,
                'unit' => $_POST['unit'],
                'purpose' => $_POST['purpose'],
                'approved_by' => $_POST['approved_by'],
                'issued_by' => Auth::id(),
                'expected_return_date' => $_POST['expected_return_date'] ?? null,
                'status' => 'Issued',
                'remarks' => $_POST['remarks'] ?? null
            ]);
            
            if (!$issueId) {
                throw new Exception("Failed to create issue record");
            }
            
            Database::update('non_lethal_weapons_inventory', [
                'current_location' => 'Issued',
                'custodian' => $_POST['officer_name'],
                'custodian_rank' => $_POST['officer_rank'],
                'custodian_nis' => $_POST['officer_nis'] ?? null
            ], 'id = ?', [$_POST['weapon_id']]);
            
            Database::commit();
            
            AuditLogger::logCreate('non_lethal_weapon_issue_log', $issueId, $_POST);
            
            $this->redirect('non_lethal_weapons/issue-log', ['success' => 'Non-lethal weapon issued successfully']);
            
        } catch (Exception $e) {
            Database::rollBack();
            error_log("Non-lethal weapon issue error: " . $e->getMessage());
            $this->redirect('non_lethal_weapons/issue', ['error' => 'Failed to issue weapon: ' . $e->getMessage()]);
        }
    }
    
    public function returnWeapon($id) {
        // Check permission
        if (!Auth::can('non_lethal_weapons.edit')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to return non-lethal weapons']);
            return;
        }
        
        $issue = Database::fetchOne(
            "SELECT nwil.*, nw.id as weapon_id, nw.weapon_id as weapon_code, nw.expiry_date
             FROM non_lethal_weapon_issue_log nwil
             JOIN non_lethal_weapons_inventory nw ON nwil.weapon_id = nw.id
             WHERE nwil.id = ?",
            [$id]
        );
        
        if (!$issue) {
            $this->redirect('non_lethal_weapons/issue-log', ['error' => 'Issue record not found']);
            return;
        }
        
        $this->view('non_lethal_weapons/return', ['issue' => $issue]);
    }
    
    public function processReturn($id) {
        // Check permission
        if (!Auth::can('non_lethal_weapons.edit')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to return non-lethal weapons']);
            return;
        }
        
        if (!Security::validateCsrfToken($_POST['csrf_token'] ?? '')) {
            $this->redirect("non_lethal_weapons/return/$id", ['error' => 'Invalid security token']);
            return;
        }
        
        $issue = Database::fetchOne("SELECT * FROM non_lethal_weapon_issue_log WHERE id = ?", [$id]);
        
        if (!$issue) {
            $this->redirect('non_lethal_weapons/issue-log', ['error' => 'Issue record not found']);
            return;
        }
        
        Database::beginTransaction();
        
        try {
            Database::update('non_lethal_weapon_issue_log', [
                'actual_return_date' => $_POST['return_date'] ?? date('Y-m-d'),
                'return_condition' => $_POST['return_condition'],
                'status' => 'Returned',
                'remarks' => $_POST['remarks'] ?? null
            ], 'id = ?', [$id]);
            
            // Update weapon location back to Armoury
            Database::update('non_lethal_weapons_inventory', [
                'current_location' => 'Armoury',
                'custodian' => null,
                'custodian_rank' => null,
                'custodian_nis' => null
            ], 'id = ?', [$issue['weapon_id']]);
            
            Database::commit();
            
            AuditLogger::logUpdate('non_lethal_weapon_issue_log', $id, $issue, $_POST);
            
            $this->redirect('non_lethal_weapons/issue-log', ['success' => 'Non-lethal weapon returned successfully']);
            
        } catch (Exception $e) {
            Database::rollBack();
            error_log("Non-lethal weapon return error: " . $e->getMessage());
            $this->redirect("non_lethal_weapons/return/$id", ['error' => 'Failed to process return: ' . $e->getMessage()]);
        }
    }
    
    public function export() {
        // Check permission
        if (!Auth::can('reports.export')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to export data']);
            return;
        }
        
        $weapons = Database::fetchAll(
            "SELECT nw.*, 
                    nwt.type_name as weapon_type_name,
                    nwc.category_name as category_name
             FROM non_lethal_weapons_inventory nw
             LEFT JOIN non_lethal_weapon_types nwt ON nw.weapon_type_id = nwt.id
             LEFT JOIN non_lethal_categories nwc ON nw.category_id = nwc.id
             ORDER BY nw.created_at DESC"
        );
        
        if ($weapons === false) $weapons = [];
        
        $filename = 'non_lethal_weapons_inventory_' . date('Y-m-d') . '.csv';
        
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        
        fputcsv($output, [
            'Weapon ID', 'Type', 'Category', 'Make/Model', 'Serial Number',
            'Ammunition Type', 'Effective Range (m)', 'Power Source', 'Less-Lethal Rating',
            'Expiry Date', 'Source', 'Condition', 'Location', 'Custodian', 'Custodian Rank',
            'Custodian NIS', 'Date Acquired', 'Last Inspection', 'Next Inspection',
            'Status', 'Remarks', 'Created At'
        ]);
        
        foreach ($weapons as $w) {
            fputcsv($output, [
                $w['weapon_id'] ?? '',
                $w['weapon_type_name'] ?? $w['weapon_type_other'] ?? '',
                $w['category_name'] ?? $w['category_other'] ?? '',
                $w['make_model'] ?? '',
                $w['serial_no'] ?? '',
                $w['ammunition_type'] ?? '',
                $w['effective_range'] ?? '',
                $w['power_source'] ?? '',
                $w['less_lethal_rating'] ?? '',
                $w['expiry_date'] ?? '',
                $w['source'] ?? '',
                $w['condition'] ?? '',
                $w['current_location'] ?? '',
                $w['custodian'] ?? '',
                $w['custodian_rank'] ?? '',
                $w['custodian_nis'] ?? '',
                $w['date_acquired'] ?? '',
                $w['last_inspection_date'] ?? '',
                $w['next_inspection_date'] ?? '',
                $w['status'] ?? '',
                $w['remarks'] ?? '',
                $w['created_at'] ?? ''
            ]);
        }
        
        fclose($output);
        
        AuditLogger::logExport('non_lethal_weapons', 'csv');
        exit;
    }
    
    public function checkExpired() {
        // Check permission
        if (!Auth::can('non_lethal_weapons.view')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission']);
            return;
        }
        
        $today = date('Y-m-d');
        $expiredWeapons = Database::fetchAll(
            "SELECT nw.*, nwt.type_name as weapon_type_name
             FROM non_lethal_weapons_inventory nw
             LEFT JOIN non_lethal_weapon_types nwt ON nw.weapon_type_id = nwt.id
             WHERE nw.expiry_date IS NOT NULL 
               AND nw.expiry_date < ?
               AND nw.status = 'Active'
             ORDER BY nw.expiry_date",
            [$today]
        );
        
        if ($expiredWeapons === false) $expiredWeapons = [];
        
        $this->view('non_lethal_weapons/expired', ['weapons' => $expiredWeapons]);
    }
}