<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\ApplicationStatus;
use App\Models\Migrant;

class AdminController extends Controller {
    
    protected $statusModel;
    protected $migrantModel;
    
    public function __construct() {
        parent::__construct();
        $this->statusModel = new ApplicationStatus();
        $this->migrantModel = new Migrant();
    }
    
    public function pending() {
        $this->requireAuth();
        
        // Only Admin and SuperAdmin can access
        if (!in_array($_SESSION['role'], ['Admin', 'SuperAdmin'])) {
            $_SESSION['error'] = 'You do not have permission to access this page';
            $this->redirect('/dashboard');
            return;
        }
        
        $pending = $this->statusModel->getPendingApplications();
        
        $this->render('admin/pending', [
            'title' => 'Pending Reviews',
            'applications' => $pending
        ]);
    }
    
    public function review($params) {
        $this->requireAuth();
        
        // Only Admin and SuperAdmin can review
        if (!in_array($_SESSION['role'], ['Admin', 'SuperAdmin'])) {
            $this->json(['error' => 'Unauthorized'], 403);
            return;
        }
        
        $person_id = $params['id'] ?? '';
        $action = $_POST['action'] ?? '';
        $remarks = $_POST['remarks'] ?? '';
        
        if (empty($person_id) || empty($action)) {
            $this->json(['error' => 'Invalid request'], 400);
            return;
        }
        
        $status = '';
        switch ($action) {
            case 'approve':
                $status = ApplicationStatus::STATUS_APPROVED;
                break;
            case 'reject':
                $status = ApplicationStatus::STATUS_REJECTED;
                break;
            case 'review':
                $status = ApplicationStatus::STATUS_UNDER_REVIEW;
                break;
            default:
                $this->json(['error' => 'Invalid action'], 400);
                return;
        }
        
        try {
            $this->statusModel->updateStatus(
                $person_id,
                $status,
                $remarks,
                $_SESSION['user_id']
            );
            
            $this->json(['success' => true, 'message' => 'Application ' . $status]);
        } catch (\Exception $e) {
            $this->json(['error' => $e->getMessage()], 400);
        }
    }
}