<?php
require_once APP_PATH . '/Core/BaseController.php';
require_once APP_PATH . '/Core/CSRF.php';

class TransitionController extends BaseController {

    public function index(): void {
        $this->view('transition.index', [
            'title' => 'University Transition Center — BOAFO',
        ]);
    }

    public function checklist(): void {
        $db     = Database::getInstance();
        $userId = Auth::id();

        // Auto-seed checklist if empty
        $stmt = $db->prepare("SELECT COUNT(*) FROM transition_checklists WHERE user_id = ?");
        $stmt->execute([$userId]);
        if ((int)$stmt->fetchColumn() === 0) {
            $this->seedChecklist($userId, $db);
        }

        $stmt2 = $db->prepare("SELECT * FROM transition_checklists WHERE user_id = ? ORDER BY category, sort_order");
        $stmt2->execute([$userId]);
        $items = $stmt2->fetchAll();

        $grouped = [];
        foreach ($items as $item) {
            $grouped[$item['category']][] = $item;
        }

        $this->view('transition.checklist', [
            'title'   => 'University Readiness Checklist — BOAFO',
            'grouped' => $grouped,
            'success' => $this->getFlash('success'),
        ]);
    }

    public function updateChecklist(): void {
        CSRF::check();
        $db     = Database::getInstance();
        $userId = Auth::id();
        $items  = $_POST['items'] ?? [];

        // Reset all
        $db->prepare("UPDATE transition_checklists SET is_completed = 0, completed_at = NULL WHERE user_id = ?")
           ->execute([$userId]);

        // Mark checked ones
        foreach ($items as $itemId) {
            $db->prepare("UPDATE transition_checklists SET is_completed = 1, completed_at = NOW() WHERE id = ? AND user_id = ?")
               ->execute([(int)$itemId, $userId]);
        }

        $this->flash('success', 'Checklist updated!');
        $this->redirect(APP_URL . '/transition/checklist');
    }

    private function seedChecklist(int $userId, \PDO $db): void {
        $items = [
            ['Academic Preparation', 'Collect your WASSCE results certificate', 0],
            ['Academic Preparation', 'Request official transcript from SHS', 1],
            ['Academic Preparation', 'Research your intended program requirements', 2],
            ['Academic Preparation', 'Check admission cutoffs for target universities', 3],
            ['Applications', 'Complete university application forms', 0],
            ['Applications', 'Pay application fees', 1],
            ['Applications', 'Submit required documents', 2],
            ['Applications', 'Track your application status', 3],
            ['Financial Planning', 'Apply for scholarships', 0],
            ['Financial Planning', 'Research student loans', 1],
            ['Financial Planning', 'Create a university budget', 2],
            ['Financial Planning', 'Set up a bank account', 3],
            ['Accommodation', 'Apply for university accommodation', 0],
            ['Accommodation', 'Research off-campus housing options', 1],
            ['Accommodation', 'Prepare packing list for dormitory', 2],
            ['Health & Wellness', 'Get required vaccinations', 0],
            ['Health & Wellness', 'Obtain National Health Insurance', 1],
            ['Health & Wellness', 'Pack a basic first-aid kit', 2],
            ['Social & Personal', 'Join university social media groups', 0],
            ['Social & Personal', 'Connect with a current student or mentor', 1],
            ['Social & Personal', 'Set personal academic goals', 2],
            ['Social & Personal', 'Read university student handbook', 3],
        ];

        $stmt = $db->prepare(
            "INSERT INTO transition_checklists (user_id, category, item, sort_order) VALUES (?, ?, ?, ?)"
        );
        foreach ($items as [$cat, $item, $order]) {
            $stmt->execute([$userId, $cat, $item, $order]);
        }
    }
}
