<?php
require_once APP_PATH . '/Core/BaseController.php';
require_once APP_PATH . '/Models/Scholarship.php';
require_once APP_PATH . '/Models/RecommendationEngine.php';

class ScholarshipController extends BaseController {

    private Scholarship $schModel;
    private RecommendationEngine $engine;

    public function __construct() {
        $this->schModel = new Scholarship();
        $this->engine   = new RecommendationEngine();
    }

    // ── GET /scholarships ────────────────────────────────────────
    public function index(): void {
        $page    = max(1, (int) ($_GET['page'] ?? 1));
        $filters = [
            'q'             => trim($_GET['q'] ?? ''),
            'category'      => $_GET['category'] ?? '',
            'type'          => $_GET['type'] ?? '',
            'status'        => $_GET['status'] ?? 'open',
            'financial_need'=> $_GET['financial_need'] ?? '',
        ];

        $result   = $this->schModel->search(array_filter($filters, fn($v) => $v !== ''), $page);
        $upcoming = $this->schModel->getUpcomingDeadlines(5);

        $this->view('scholarships.index', [
            'title'       => 'Scholarship Intelligence Center — BOAFO',
            'scholarships'=> $result['items'],
            'pagination'  => $result,
            'filters'     => $filters,
            'upcoming'    => $upcoming,
        ]);
    }

    // ── GET /scholarships/{slug} ─────────────────────────────────
    public function show(string $slug): void {
        $scholarship = $this->schModel->getWithLinkedUniversities($slug);
        if (!$scholarship) {
            http_response_code(404);
            $this->view('errors.error', ['title'=>'Not Found','code'=>404,'message'=>'Scholarship not found.']);
            return;
        }

        $isSaved = Auth::check() ? $this->schModel->isSaved(Auth::id(), $scholarship['id']) : false;

        $this->view('scholarships.show', [
            'title'       => $scholarship['name'] . ' — BOAFO',
            'scholarship' => $scholarship,
            'is_saved'    => $isSaved,
        ]);
    }

    // ── POST /scholarships/{id}/save ─────────────────────────────
    public function save(string $id): void {
        $this->schModel->save(Auth::id(), (int) $id);
        if ($this->isAjax()) $this->json(['success'=>true,'saved'=>true]);
        $this->back();
    }

    // ── POST /scholarships/{id}/unsave ───────────────────────────
    public function unsave(string $id): void {
        $this->schModel->unsave(Auth::id(), (int) $id);
        if ($this->isAjax()) $this->json(['success'=>true,'saved'=>false]);
        $this->back();
    }

    // ── GET /scholarships/recommended ────────────────────────────
    public function recommended(): void {
        $recommendations = $this->engine->recommendScholarships(Auth::id());
        $this->view('scholarships.recommended', [
            'title'           => 'Recommended Scholarships — BOAFO',
            'recommendations' => $recommendations,
        ]);
    }

    // ── POST /api/scholarships/recommend ─────────────────────────
    public function ajaxRecommend(): void {
        CSRF::check();
        $recommendations = $this->engine->recommendScholarships(Auth::id());
        $this->json(['success'=>true,'data'=>$recommendations]);
    }

    // ── POST /api/scholarship/predict ────────────────────────────
    public function predict(): void {
        CSRF::check();
        $scholarshipId = (int) $this->input('scholarship_id', 0);
        if (!$scholarshipId) {
            $this->json(['success'=>false,'message'=>'Missing scholarship ID.'], 400);
        }
        $result = $this->engine->predictScholarshipSuccess($scholarshipId, Auth::id());
        $this->json(['success'=>true,'data'=>$result]);
    }

    // ── GET /api/scholarships/search ─────────────────────────────
    public function ajaxSearch(): void {
        $q = trim($_GET['q'] ?? '');
        $result = $this->schModel->search(['q'=>$q,'status'=>'open'], 1);
        $items = array_map(fn($s) => [
            'id'       => $s['id'],
            'name'     => $s['name'],
            'provider' => $s['provider'],
            'type'     => $s['scholarship_type'],
            'deadline' => $s['application_deadline'],
            'slug'     => $s['slug'],
        ], $result['items']);
        $this->json(['results'=>$items]);
    }
}

require_once APP_PATH . '/Core/CSRF.php';
