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

class UniversityController extends BaseController {

    private University $uniModel;

    public function __construct() {
        $this->uniModel = new University();
    }

    // ── GET /universities ────────────────────────────────────────
    public function index(): void {
        $page    = max(1, (int) ($_GET['page'] ?? 1));
        $filters = [
            'q'          => trim($_GET['q'] ?? ''),
            'country_id' => (int) ($_GET['country_id'] ?? 0) ?: null,
            'type'       => $_GET['type'] ?? '',
            'region_id'  => (int) ($_GET['region_id'] ?? 0) ?: null,
        ];

        $result  = $this->uniModel->search(array_filter($filters), $page);
        $db      = Database::getInstance();
        $countries = $db->query("SELECT * FROM countries ORDER BY name")->fetchAll();
        $regions   = $db->query("SELECT * FROM regions WHERE country_id = 1 ORDER BY name")->fetchAll();

        $this->view('universities.index', [
            'title'      => 'University Discovery Center — BOAFO',
            'pagination' => $result,
            'universities'=> $result['items'],
            'filters'    => $filters,
            'countries'  => $countries,
            'regions'    => $regions,
        ]);
    }

    // ── GET /universities/{slug} ─────────────────────────────────
    public function show(string $slug): void {
        $university = $this->uniModel->getWithDetails($slug);
        if (!$university) {
            http_response_code(404);
            $this->view('errors.error', ['title' => 'University Not Found', 'code' => 404, 'message' => 'The university you are looking for does not exist.']);
            return;
        }

        $programs     = $this->uniModel->getPrograms($university['id']);
        $mentors      = $this->uniModel->getMentors($university['id']);
        $scholarships = $this->uniModel->getScholarships($university['id']);
        $reviews      = $this->uniModel->getReviews($university['id']);
        $avgRating    = $this->uniModel->getAverageRating($university['id']);
        $isSaved      = Auth::check() ? $this->uniModel->isSaved(Auth::id(), $university['id']) : false;

        $this->view('universities.show', [
            'title'        => $university['name'] . ' — BOAFO',
            'university'   => $university,
            'programs'     => $programs,
            'mentors'      => $mentors,
            'scholarships' => $scholarships,
            'reviews'      => $reviews,
            'avg_rating'   => $avgRating,
            'is_saved'     => $isSaved,
        ]);
    }

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

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

    // ── GET /api/universities/search ─────────────────────────────
    public function ajaxSearch(): void {
        $q       = trim($_GET['q'] ?? '');
        $results = $this->uniModel->search(['q' => $q], 1);
        $items   = array_map(fn($u) => [
            'id'   => $u['id'],
            'name' => $u['name'],
            'city' => $u['city'],
            'type' => $u['university_type'],
            'slug' => $u['slug'],
            'logo' => logoUrl($u['logo']),
        ], $results['items']);
        $this->json(['results' => $items]);
    }

    // ── GET /universities/{slug}/programs ────────────────────────
    public function programs(string $slug): void {
        $university = $this->uniModel->getWithDetails($slug);
        if (!$university) { http_response_code(404); return; }
        $programs = $this->uniModel->getPrograms($university['id']);
        $this->view('universities.programs', [
            'title'      => "Programs — {$university['name']} — BOAFO",
            'university' => $university,
            'programs'   => $programs,
        ]);
    }

    // ── GET /universities/{slug}/mentors ─────────────────────────
    public function mentors(string $slug): void {
        $university = $this->uniModel->getWithDetails($slug);
        if (!$university) { http_response_code(404); return; }
        $mentors = $this->uniModel->getMentors($university['id'], 20);
        $this->view('universities.mentors', [
            'title'      => "Mentors — {$university['name']} — BOAFO",
            'university' => $university,
            'mentors'    => $mentors,
        ]);
    }

    // ── GET /universities/{slug}/scholarships ────────────────────
    public function scholarships(string $slug): void {
        $university   = $this->uniModel->getWithDetails($slug);
        if (!$university) { http_response_code(404); return; }
        $scholarships = $this->uniModel->getScholarships($university['id']);
        $this->view('universities.scholarships', [
            'title'        => "Scholarships — {$university['name']} — BOAFO",
            'university'   => $university,
            'scholarships' => $scholarships,
        ]);
    }
}
