<?php
/**
 * Returns Controller
 */
class ReturnsController extends Controller {
    
    /**
     * Constructor
     */
    public function __construct() {
        // Only call parent constructor if it exists
        if (method_exists(get_parent_class($this), '__construct')) {
            parent::__construct();
        }
    }
    
    /**
     * Display all returns
     */
    public function index() {
        // Check permission
        if (!Auth::can('returns.view')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to view returns']);
            return;
        }
        
        $returns = Database::fetchAll(
            "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
             ORDER BY r.created_at DESC"
        );
        
        if ($returns === false) $returns = [];
        
        // Calculate statistics
        $statistics = [
            'total' => count($returns),
            'pending' => 0,
            'processed' => 0,
            'verified' => 0,
            'completed' => 0,
            'total_weapons_returned' => 0,
            'total_ammunition_returned' => 0
        ];
        
        foreach ($returns as $return) {
            $status = $return['status'] ?? '';
            switch ($status) {
                case 'Pending':
                    $statistics['pending']++;
                    break;
                case 'Processed':
                    $statistics['processed']++;
                    break;
                case 'Verified':
                    $statistics['verified']++;
                    break;
                case 'Completed':
                    $statistics['completed']++;
                    break;
            }
        }
        
        // Get weapons and ammunition counts from related tables
        // This would need to be implemented based on your database structure
        
        $this->view('returns/index', [
            'returns' => $returns,
            'statistics' => $statistics
        ]);
    }
    
    /**
 * Show create return form
 */
public function create() {
    // Check permission
    if (!Auth::can('returns.create')) {
        $this->redirect('dashboard', ['error' => 'You do not have permission to create returns']);
        return;
    }
    
    // Get available weapons (issued weapons that can be returned)
    $availableWeapons = Database::fetchAll(
        "SELECT wi.*, wt.type_name 
         FROM weapons_inventory wi
         LEFT JOIN weapon_types wt ON wi.weapon_type_id = wt.id
         WHERE wi.current_location = 'Issued'
         ORDER BY wi.weapon_id"
    ) ?: [];
    
    // Get issued ammunition
    $issuedAmmunition = Database::fetchAll(
        "SELECT ai.*, at.ammo_type, ac.calibre
         FROM ammunition_inventory ai
         LEFT JOIN ammunition_types at ON ai.ammo_type_id = at.id
         LEFT JOIN ammunition_calibres ac ON ai.calibre_id = ac.id
         WHERE ai.quantity_issued > 0
         ORDER BY ai.ammo_id"
    ) ?: [];
    
    // Get ALL requisitions for the dropdown (not just issued ones)
    $requisitions = Database::fetchAll(
        "SELECT r.*, 
                u.full_name as requesting_officer_name,
                COUNT(ri.id) as total_items
         FROM requisitions r
         LEFT JOIN users u ON r.requesting_officer_id = u.id
         LEFT JOIN requisition_items ri ON r.id = ri.requisition_id
         GROUP BY r.id
         ORDER BY r.created_at DESC"
    ) ?: [];
    
    $this->view('returns/create', [
        'availableWeapons' => $availableWeapons,
        'issuedAmmunition' => $issuedAmmunition,
        'requisitions' => $requisitions  // This is the key change
    ]);
}
    
 /**
 * Store new return (simplified version)
 */
public function store() {
    // Check permission
    if (!Auth::can('returns.create')) {
        $this->redirect('dashboard', ['error' => 'You do not have permission to create returns']);
        return;
    }
    
    // Validate CSRF token
    if (!Security::validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $this->redirect('returns/create', ['error' => 'Invalid security token']);
        return;
    }
    
    // Manual validation
    $errors = [];
    
    if (empty($_POST['return_date'])) {
        $errors['return_date'] = 'Return date is required';
    }
    
    if (empty($_POST['return_type'])) {
        $errors['return_type'] = 'Return type is required';
    }
    
    if (empty($_POST['returning_officer_name'])) {
        $errors['returning_officer_name'] = 'Officer name is required';
    }
    
    if (empty($_POST['returning_rank'])) {
        $errors['returning_rank'] = 'Rank is required';
    }
    
    if (empty($_POST['returning_nis'])) {
        $errors['returning_nis'] = 'NIS number is required';
    }
    
    if (empty($_POST['returning_unit'])) {
        $errors['returning_unit'] = 'Unit is required';
    }
    
    // Check if at least one weapon or ammunition is provided based on return type
    $returnType = $_POST['return_type'] ?? '';
    $hasWeapon = isset($_POST['weapon_id']) && is_array($_POST['weapon_id']) && !empty(array_filter($_POST['weapon_id']));
    $hasAmmo = isset($_POST['ammo_id']) && is_array($_POST['ammo_id']) && !empty(array_filter($_POST['ammo_id']));
    
    if ($returnType === 'Weapon' && !$hasWeapon) {
        $errors['weapons'] = 'At least one weapon is required';
    }
    
    if ($returnType === 'Ammunition' && !$hasAmmo) {
        $errors['ammunition'] = 'At least one ammunition is required';
    }
    
    if ($returnType === 'Both' && (!$hasWeapon || !$hasAmmo)) {
        $errors['items'] = 'Both weapons and ammunition are required';
    }
    
    if (!empty($errors)) {
        Session::set('errors', $errors);
        Session::set('old', $_POST);
        $this->redirect('returns/create');
        return;
    }
    
    $returnNumber = $this->generateReturnNumber();
    
    Database::beginTransaction();
    
    try {
        // For this simplified version, we'll only handle the first weapon and first ammunition
        $weaponId = isset($_POST['weapon_id']) && is_array($_POST['weapon_id']) ? $_POST['weapon_id'][0] : null;
        $weaponCondition = isset($_POST['condition']) && is_array($_POST['condition']) ? $_POST['condition'][0] : null;
        $weaponRemarks = isset($_POST['weapon_remarks']) && is_array($_POST['weapon_remarks']) ? $_POST['weapon_remarks'][0] : null;
        
        $ammoId = isset($_POST['ammo_id']) && is_array($_POST['ammo_id']) ? $_POST['ammo_id'][0] : null;
        $batchNumber = isset($_POST['batch_number']) && is_array($_POST['batch_number']) ? $_POST['batch_number'][0] : null;
        $roundsReturned = isset($_POST['rounds_returned']) && is_array($_POST['rounds_returned']) ? (int)$_POST['rounds_returned'][0] : 0;
        $ammoCondition = isset($_POST['ammo_condition']) && is_array($_POST['ammo_condition']) ? $_POST['ammo_condition'][0] : null;
        $ammoRemarks = isset($_POST['ammo_remarks']) && is_array($_POST['ammo_remarks']) ? $_POST['ammo_remarks'][0] : null;
        
        // Insert return record
        $returnId = Database::insert('returns', [
            'return_number' => $returnNumber,
            'return_date' => $_POST['return_date'],
            'return_type' => $_POST['return_type'],
            'requisition_id' => !empty($_POST['requisition_id']) ? $_POST['requisition_id'] : null,
            'returning_officer_name' => $_POST['returning_officer_name'],
            'returning_rank' => $_POST['returning_rank'],
            'returning_nis' => $_POST['returning_nis'],
            'returning_unit' => $_POST['returning_unit'],
            'weapon_id' => $weaponId,
            'weapon_condition' => $weaponCondition,
            'weapon_remarks' => $weaponRemarks,
            'ammo_id' => $ammoId,
            'batch_number' => $batchNumber,
            'rounds_returned' => $roundsReturned,
            'ammo_condition' => $ammoCondition,
            'ammo_remarks' => $ammoRemarks,
            'status' => 'Pending',
            'remarks' => $_POST['remarks'] ?? null,
            'created_by' => Auth::id(),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        
        if (!$returnId) {
            throw new Exception("Failed to create return record");
        }
        
        // Update weapon status if weapon was returned
        if ($weaponId) {
            Database::update('weapons_inventory', [
                'current_location' => 'Armoury',
                'custodian' => null,
                'custodian_rank' => null,
                'custodian_nis' => null,
                'updated_at' => date('Y-m-d H:i:s')
            ], 'id = ?', [$weaponId]);
        }
        
        // Update ammunition balance if ammunition was returned
        if ($ammoId && $roundsReturned > 0) {
            $ammo = Database::fetchOne("SELECT * FROM ammunition_inventory WHERE id = ?", [$ammoId]);
            if ($ammo) {
                $newIssued = ($ammo['quantity_issued'] ?? 0) - $roundsReturned;
                $newBalance = ($ammo['quantity_received'] ?? 0) - $newIssued;
                
                Database::update('ammunition_inventory', [
                    'quantity_issued' => $newIssued,
                    'balance' => $newBalance,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$ammoId]);
            }
        }
        
        Database::commit();
        
        if (class_exists('AuditLogger')) {
            AuditLogger::logCreate('returns', $returnId, $_POST);
        }
        
        $this->redirect('returns', ['success' => 'Return created successfully']);
        
    } catch (Exception $e) {
        Database::rollBack();
        error_log("Return creation error: " . $e->getMessage());
        Session::set('errors', ['general' => 'Failed to create return: ' . $e->getMessage()]);
        Session::set('old', $_POST);
        $this->redirect('returns/create');
    }
}
    /**
     * Show return details
     */
    public function show($id) {
        // Check permission
        if (!Auth::can('returns.view')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to view returns']);
            return;
        }
        
        $return = Database::fetchOne(
            "SELECT r.*, u.full_name as received_by_name, req.requisition_number,
                    creator.full_name as created_by_name
             FROM returns r
             LEFT JOIN users u ON r.received_by = u.id
             LEFT JOIN requisitions req ON r.requisition_id = req.id
             LEFT JOIN users creator ON r.created_by = creator.id
             WHERE r.id = ?",
            [$id]
        );
        
        if (!$return) {
            $this->redirect('returns', ['error' => 'Return not found']);
            return;
        }
        
        // Get returned weapons
        $weapons = Database::fetchAll(
            "SELECT rw.*, wi.weapon_id, wi.make_model, wi.serial_no, wt.type_name
             FROM return_weapons rw
             JOIN weapons_inventory wi ON rw.weapon_id = wi.id
             LEFT JOIN weapon_types wt ON wi.weapon_type_id = wt.id
             WHERE rw.return_id = ?",
            [$id]
        ) ?: [];
        
        // Get returned ammunition
        $ammunition = Database::fetchAll(
            "SELECT ra.*, ai.ammo_id, ai.ammo_type, ai.calibre
             FROM return_ammunition ra
             JOIN ammunition_inventory ai ON ra.ammo_id = ai.id
             WHERE ra.return_id = ?",
            [$id]
        ) ?: [];
        
        if (class_exists('AuditLogger')) {
            AuditLogger::logView('returns', $id);
        }
        
        $this->view('returns/show', [
            'return' => $return,
            'weapons' => $weapons,
            'ammunition' => $ammunition
        ]);
    }
    
    /**
     * Process return (mark as received)
     */
    public function process($id) {
        // Check permission
        if (!Auth::can('returns.process')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to process returns']);
            return;
        }
        
        $return = Database::fetchOne("SELECT * FROM returns WHERE id = ?", [$id]);
        
        if (!$return) {
            $this->redirect('returns', ['error' => 'Return not found']);
            return;
        }
        
        if ($return['status'] !== 'Pending') {
            $this->redirect('returns', ['error' => 'Only pending returns can be processed']);
            return;
        }
        
        Database::beginTransaction();
        
        try {
            Database::update('returns', [
                'status' => 'Processed',
                'received_by' => Auth::id(),
                'updated_at' => date('Y-m-d H:i:s')
            ], 'id = ?', [$id]);
            
            Database::commit();
            
            if (class_exists('AuditLogger')) {
                AuditLogger::log('PROCESS', 'returns', $id, null, 'Return processed');
            }
            
            $this->redirect('returns', ['success' => 'Return processed successfully']);
            
        } catch (Exception $e) {
            Database::rollBack();
            error_log("Return process error: " . $e->getMessage());
            $this->redirect("returns/show/$id", ['error' => 'Failed to process return: ' . $e->getMessage()]);
        }
    }
    
    /**
     * Generate unique return number
     */
    private function generateReturnNumber() {
        $year = date('Y');
        $month = date('m');
        
        $last = Database::fetchOne(
            "SELECT return_number FROM returns
             WHERE return_number LIKE 'RET-{$year}{$month}%' 
             ORDER BY id DESC LIMIT 1"
        );
        
        if ($last && isset($last['return_number'])) {
            $seq = intval(substr($last['return_number'], -4)) + 1;
        } else {
            $seq = 1;
        }
        
        return sprintf("RET-%s%s-%04d", $year, $month, $seq);
    }
    
    /**
     * Export returns to CSV
     */
    public function export() {
        // Check permission
        if (!Auth::can('reports.export')) {
            $this->redirect('dashboard', ['error' => 'You do not have permission to export data']);
            return;
        }
        
        $returns = Database::fetchAll(
            "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
             ORDER BY r.created_at DESC"
        );
        
        if ($returns === false) $returns = [];
        
        $filename = 'returns_' . date('Y-m-d') . '.csv';
        
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        
        // Headers
        fputcsv($output, [
            'Return #', 'Date', 'Type', 'Requisition #', 'Returning Officer',
            'Rank', 'NIS Number', 'Unit', 'Status', 'Remarks', 'Created At'
        ]);
        
        // Data
        foreach ($returns as $return) {
            fputcsv($output, [
                $return['return_number'] ?? '',
                $return['return_date'] ?? '',
                $return['return_type'] ?? '',
                $return['requisition_number'] ?? '',
                $return['returning_officer_name'] ?? '',
                $return['returning_rank'] ?? '',
                $return['returning_nis'] ?? '',
                $return['returning_unit'] ?? '',
                $return['status'] ?? '',
                $return['remarks'] ?? '',
                $return['created_at'] ?? ''
            ]);
        }
        
        fclose($output);
        
        if (class_exists('AuditLogger')) {
            AuditLogger::logExport('returns', 'csv');
        }
        exit;
    }
}