<?php
/**
 * API Controller for handling AJAX requests
 */
class ApiController extends Controller {
    
    /**
     * Get dashboard statistics
     */
    public function dashboardStats() {
        // Check if AJAX request
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        // Get statistics
        $stats = [
            'total_weapons' => $this->getTotalWeapons(),
            'issued_weapons' => $this->getIssuedWeaponsCount(),
            'available_weapons' => $this->getAvailableWeaponsCount(),
            'serviceable_weapons' => $this->getServiceableWeapons(),
            'unserviceable_weapons' => $this->getUnserviceableWeapons(),
            'total_ammunition' => $this->getTotalAmmunition(),
            'available_ammo' => $this->getAvailableAmmoCount(),
            'pending_returns' => $this->getPendingReturns()
        ];
        
        $this->jsonResponse(true, 'Success', $stats);
    }
    
    /**
     * Get LGAs by state
     */
    public function getLgas() {
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        $stateId = $_GET['state_id'] ?? 0;
        
        if (!$stateId) {
            echo json_encode([]);
            exit;
        }
        
        $lgas = Database::fetchAll(
            "SELECT id, lga_name FROM lgas WHERE state_id = ? ORDER BY lga_name",
            [$stateId]
        );
        
        echo json_encode($lgas);
        exit;
    }
    
    /**
     * Get commands by zone
     */
    public function getCommands() {
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        $zoneId = $_GET['zone_id'] ?? 0;
        
        if (!$zoneId) {
            echo json_encode([]);
            exit;
        }
        
        $commands = Database::fetchAll(
            "SELECT id, command_name FROM commands WHERE zone_id = ? ORDER BY command_name",
            [$zoneId]
        );
        
        echo json_encode($commands);
        exit;
    }
    
    /**
     * Get weapons list
     */
    public function getWeapons() {
        Auth::requirePermission('weapons.view');
        
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        $search = $_GET['search'] ?? '';
        
        if ($search) {
            $weapons = Database::fetchAll(
                "SELECT w.*, wt.type_name 
                 FROM weapons_inventory w
                 LEFT JOIN weapon_types wt ON w.weapon_type_id = wt.id
                 WHERE w.weapon_id LIKE ? 
                 OR w.serial_no LIKE ? 
                 OR w.make_model LIKE ?
                 ORDER BY w.created_at DESC
                 LIMIT 50",
                ["%$search%", "%$search%", "%$search%"]
            );
        } else {
            $weapons = Database::fetchAll(
                "SELECT w.*, wt.type_name 
                 FROM weapons_inventory w
                 LEFT JOIN weapon_types wt ON w.weapon_type_id = wt.id
                 ORDER BY w.created_at DESC
                 LIMIT 50"
            );
        }
        
        echo json_encode(['success' => true, 'data' => $weapons]);
        exit;
    }
    
    /**
     * Get ammunition list
     */
    public function getAmmunition() {
        Auth::requirePermission('ammunition.view');
        
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        $search = $_GET['search'] ?? '';
        
        if ($search) {
            $ammunition = Database::fetchAll(
                "SELECT a.*, at.ammo_type, ac.calibre
                 FROM ammunition_inventory a
                 LEFT JOIN ammunition_types at ON a.ammo_type_id = at.id
                 LEFT JOIN ammunition_calibres ac ON a.calibre_id = ac.id
                 WHERE a.ammo_id LIKE ? 
                 OR a.batch_number LIKE ?
                 OR at.ammo_type LIKE ?
                 OR ac.calibre LIKE ?
                 ORDER BY a.created_at DESC
                 LIMIT 50",
                ["%$search%", "%$search%", "%$search%", "%$search%"]
            );
        } else {
            $ammunition = Database::fetchAll(
                "SELECT a.*, at.ammo_type, ac.calibre
                 FROM ammunition_inventory a
                 LEFT JOIN ammunition_types at ON a.ammo_type_id = at.id
                 LEFT JOIN ammunition_calibres ac ON a.calibre_id = ac.id
                 ORDER BY a.created_at DESC
                 LIMIT 50"
            );
        }
        
        echo json_encode(['success' => true, 'data' => $ammunition]);
        exit;
    }
    
    /**
     * Get requisitions list
     */
    public function getRequisitions() {
        Auth::requirePermission('requisition.view');
        
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        $status = $_GET['status'] ?? '';
        $userId = $_GET['user_id'] ?? '';
        
        $sql = "SELECT r.*, u.full_name as requester_name, c.command_name
                FROM requisitions r
                LEFT JOIN users u ON r.requesting_officer_id = u.id
                LEFT JOIN commands c ON r.requesting_command_id = c.id
                WHERE 1=1";
        $params = [];
        
        if ($status) {
            $sql .= " AND r.status = ?";
            $params[] = $status;
        }
        
        if ($userId) {
            $sql .= " AND r.created_by = ?";
            $params[] = $userId;
        }
        
        $sql .= " ORDER BY r.created_at DESC LIMIT 100";
        
        $requisitions = Database::fetchAll($sql, $params);
        
        echo json_encode(['success' => true, 'data' => $requisitions]);
        exit;
    }
    
    /**
     * Get returns log
     */
    public function getReturnsLog() {
        Auth::requirePermission('returns.view');
        
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        $search = $_GET['search'] ?? '';
        $status = $_GET['status'] ?? '';
        
        $sql = "SELECT r.*, u.full_name as received_by_name, req.requisition_number
                FROM returns r
                LEFT JOIN users u ON r.received_by = u.id
                LEFT JOIN requisitions req ON r.requisition_id = req.id
                WHERE 1=1";
        $params = [];
        
        if ($search) {
            $sql .= " AND (r.return_number LIKE ? OR r.returning_officer_name LIKE ? OR r.returning_unit LIKE ?)";
            $searchTerm = "%$search%";
            $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm]);
        }
        
        if ($status) {
            $sql .= " AND r.status = ?";
            $params[] = $status;
        }
        
        $sql .= " ORDER BY r.created_at DESC LIMIT 100";
        
        $returns = Database::fetchAll($sql, $params);
        
        // Get counts for each return
        foreach ($returns as &$return) {
            $weapons = Database::fetchOne(
                "SELECT COUNT(*) as count, SUM(arm_total) as total FROM return_weapons WHERE return_id = ?",
                [$return['id']]
            );
            $return['weapons_count'] = $weapons['count'] ?? 0;
            $return['weapons_total'] = $weapons['total'] ?? 0;
            
            $ammo = Database::fetchOne(
                "SELECT COUNT(*) as count, SUM(rounds_returned) as total FROM return_ammunition WHERE return_id = ?",
                [$return['id']]
            );
            $return['ammo_count'] = $ammo['count'] ?? 0;
            $return['ammo_total'] = $ammo['total'] ?? 0;
        }
        
        echo json_encode(['success' => true, 'data' => $returns]);
        exit;
    }
    
    /**
     * Update inventory
     */
    public function updateInventory() {
        Auth::requirePermission('weapons.edit');
        
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            exit;
        }
        
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        if (!Security::validateCsrfToken($_POST['csrf_token'] ?? '')) {
            echo json_encode(['success' => false, 'message' => 'Invalid security token']);
            exit;
        }
        
        $type = $_POST['type'] ?? '';
        $id = $_POST['id'] ?? 0;
        $field = $_POST['field'] ?? '';
        $value = $_POST['value'] ?? '';
        
        if (!$type || !$id || !$field) {
            echo json_encode(['success' => false, 'message' => 'Missing required fields']);
            exit;
        }
        
        $allowedFields = [
            'weapons' => ['condition', 'current_location', 'custodian', 'remarks'],
            'ammunition' => ['condition', 'storage_location', 'remarks']
        ];
        
        if (!in_array($field, $allowedFields[$type] ?? [])) {
            echo json_encode(['success' => false, 'message' => 'Field not allowed']);
            exit;
        }
        
        $table = $type === 'weapons' ? 'weapons_inventory' : 'ammunition_inventory';
        $oldData = Database::fetchOne("SELECT * FROM $table WHERE id = ?", [$id]);
        
        if (!$oldData) {
            echo json_encode(['success' => false, 'message' => 'Record not found']);
            exit;
        }
        
        Database::beginTransaction();
        
        try {
            Database::update($table, [$field => $value], 'id = ?', [$id]);
            
            AuditLogger::logUpdate($table, $id, $oldData, [$field => $value]);
            
            Database::commit();
            
            echo json_encode(['success' => true, 'message' => 'Updated successfully']);
            
        } catch (Exception $e) {
            Database::rollBack();
            error_log("Update inventory error: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'Update failed']);
        }
        exit;
    }
    
    /**
     * Validate serial number
     */
    public function validateSerial() {
        Auth::requireAuth();
        
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        $type = $_GET['type'] ?? '';
        $serial = $_GET['serial'] ?? '';
        $excludeId = $_GET['exclude_id'] ?? null;
        
        if (!$type || !$serial) {
            echo json_encode(['valid' => false, 'message' => 'Missing required fields']);
            exit;
        }
        
        $exists = false;
        
        if ($type === 'weapon') {
            $sql = "SELECT COUNT(*) as count FROM weapons_inventory WHERE serial_no = ?";
            $params = [$serial];
            
            if ($excludeId) {
                $sql .= " AND id != ?";
                $params[] = $excludeId;
            }
            
            $result = Database::fetchOne($sql, $params);
            $exists = ($result['count'] ?? 0) > 0;
        } elseif ($type === 'ammunition') {
            // Check ammunition batch number uniqueness if needed
            $sql = "SELECT COUNT(*) as count FROM ammunition_inventory WHERE batch_number = ?";
            $params = [$serial];
            
            if ($excludeId) {
                $sql .= " AND id != ?";
                $params[] = $excludeId;
            }
            
            $result = Database::fetchOne($sql, $params);
            $exists = ($result['count'] ?? 0) > 0;
        }
        
        echo json_encode([
            'valid' => !$exists,
            'exists' => $exists,
            'message' => $exists ? 'Serial number already exists' : 'Serial number is available'
        ]);
        exit;
    }
    
    /**
     * Get audit details
     */
    public function getAuditDetails() {
        Auth::requirePermission('audit.view');
        
        if (!$this->isAjax()) {
            header('HTTP/1.0 403 Forbidden');
            exit;
        }
        
        $auditId = $_GET['audit_id'] ?? 0;
        
        if (!$auditId) {
            echo json_encode(['success' => false, 'message' => 'Audit ID required']);
            exit;
        }
        
        $weapons = Database::fetchAll(
            "SELECT aw.*, wi.weapon_id, wi.make_model, wi.serial_no
             FROM audit_weapons aw
             JOIN weapons_inventory wi ON aw.weapon_id = wi.id
             WHERE aw.audit_id = ?",
            [$auditId]
        );
        
        $ammunition = Database::fetchAll(
            "SELECT aa.*, ai.ammo_id, ai.ammo_type, ai.calibre
             FROM audit_ammunition aa
             JOIN ammunition_inventory ai ON aa.ammo_id = ai.id
             WHERE aa.audit_id = ?",
            [$auditId]
        );
        
        echo json_encode([
            'success' => true,
            'weapons' => $weapons,
            'ammunition' => $ammunition
        ]);
        exit;
    }
    
    // =============================================
    // PRIVATE HELPER METHODS
    // =============================================
    
    /**
     * Get total weapons count
     */
    private function getTotalWeapons() {
        $result = Database::fetchOne("SELECT COUNT(*) as count FROM weapons_inventory");
        return $result['count'] ?? 0;
    }
    
    /**
     * Get issued weapons count
     */
    private function getIssuedWeaponsCount() {
        $result = Database::fetchOne("SELECT COUNT(*) as count FROM weapons_inventory WHERE current_location = 'Issued'");
        return $result['count'] ?? 0;
    }
    
    /**
     * Get available weapons count
     */
    private function getAvailableWeaponsCount() {
        $result = Database::fetchOne("SELECT COUNT(*) as count FROM weapons_inventory WHERE current_location = 'Armoury' OR current_location = 'Available'");
        return $result['count'] ?? 0;
    }
    
    /**
     * Get serviceable weapons count
     */
    private function getServiceableWeapons() {
        $result = Database::fetchOne("SELECT COUNT(*) as count FROM weapons_inventory WHERE `condition` = 'Serviceable'");
        return $result['count'] ?? 0;
    }
    
    /**
     * Get unserviceable weapons count
     */
    private function getUnserviceableWeapons() {
        $result = Database::fetchOne("SELECT COUNT(*) as count FROM weapons_inventory WHERE `condition` = 'Unserviceable'");
        return $result['count'] ?? 0;
    }
    
    /**
     * Get total ammunition count
     */
    private function getTotalAmmunition() {
        $result = Database::fetchOne("SELECT COUNT(*) as count FROM ammunition_inventory");
        return $result['count'] ?? 0;
    }
    
    /**
     * Get available ammo types count
     */
    private function getAvailableAmmoCount() {
        $result = Database::fetchOne("SELECT COUNT(*) as count FROM ammunition_inventory WHERE balance > 0");
        return $result['count'] ?? 0;
    }
    
    /**
     * Get pending returns count
     */
    private function getPendingReturns() {
        $result = Database::fetchOne("SELECT COUNT(*) as count FROM weapon_issue_log WHERE status = 'Issued' AND expected_return_date < CURDATE()");
        return $result['count'] ?? 0;
    }
    
    /**
     * Check if AJAX request
     */
    protected function isAjax() {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
    
    /**
     * Send JSON response
     */
    protected function jsonResponse($success, $message, $data = []) {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => $success,
            'message' => $message,
            'stats' => $data
        ]);
        exit;
    }
}