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

class CareerController extends BaseController {

    public function index(): void {
        $db         = Database::getInstance();
        
        $search = $_GET['search'] ?? '';
        $category = $_GET['category'] ?? '';

        // Query Categories
        $cats = $db->query("SELECT name FROM career_categories ORDER BY name")->fetchAll(PDO::FETCH_COLUMN);
        
        // Build Career Query
        $sql = "SELECT ca.*, cc.name AS category,
                       ca.description AS overview,
                       ca.required_programs AS education_required,
                       CONCAT('GHS ', ca.avg_salary_ghs) AS avg_salary
                FROM careers ca 
                LEFT JOIN career_categories cc ON cc.id = ca.category_id 
                WHERE 1=1";
        $params = [];

        if (!empty($search)) {
            $sql .= " AND ca.title LIKE ?";
            $params[] = "%$search%";
        }

        if (!empty($category)) {
            $sql .= " AND cc.name = ?";
            $params[] = $category;
        }

        $sql .= " ORDER BY cc.name, ca.title";

        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $guides = $stmt->fetchAll();

        $this->view('careers.index', [
            'title'            => 'Career Guidance Center — BOAFO',
            'categories'       => $cats,
            'guides'           => $guides,
            'search'           => $search,
            'selectedCategory' => $category,
        ]);
    }

    public function show(string $slug): void {
        $db     = Database::getInstance();
        $stmt   = $db->prepare(
            "SELECT ca.*, cc.name AS category,
                    ca.description AS overview,
                    ca.required_programs AS education_required,
                    CONCAT('GHS ', ca.avg_salary_ghs) AS avg_salary,
                    ca.growth_outlook AS job_outlook,
                    ca.career_path AS education_pathway,
                    ca.skills_required AS key_skills
             FROM careers ca
             LEFT JOIN career_categories cc ON cc.id = ca.category_id
             WHERE ca.slug = ?"
        );
        $stmt->execute([$slug]);
        $guide = $stmt->fetch();

        if (!$guide) {
            http_response_code(404);
            $this->view('errors.error', ['title'=>'Not Found','code'=>404,'message'=>'Career not found.']);
            return;
        }

        // Related programs
        $relatedPrograms = $db->query(
            "SELECT p.name, u.name AS university_name, u.slug AS university_slug
             FROM programs p JOIN universities u ON u.id = p.university_id
             WHERE p.is_active = 1
             ORDER BY RAND() LIMIT 5"
        )->fetchAll();

        $this->view('careers.show', [
            'title'           => $guide['title'] . ' Career — BOAFO',
            'guide'           => $guide,
            'relatedPrograms' => $relatedPrograms,
        ]);
    }

    public function assessment(): void {
        $this->view('careers.assessment', [
            'title' => 'Career Assessment — BOAFO',
        ]);
    }

    public function submitAssessment(): void {
        CSRF::check();
        $responses = $_POST['responses'] ?? [];
        if (empty($responses)) {
            $this->flash('error', 'Please answer the assessment questions.');
            $this->redirect(APP_URL . '/career-assessment');
        }

        // Simple scoring
        $scores = [];
        foreach ($responses as $q => $answer) {
            $scores[$answer] = ($scores[$answer] ?? 0) + 1;
        }
        arsort($scores);
        $topCareer = array_key_first($scores);

        $db = Database::getInstance();
        $db->prepare("INSERT INTO career_assessments (user_id, responses, results, completed_at) VALUES (?, ?, ?, NOW())")
           ->execute([Auth::id(), json_encode($responses), json_encode($scores)]);

        $this->view('careers.assessment_result', [
            'title'     => 'Career Assessment Results — BOAFO',
            'scores'    => $scores,
            'top_career'=> $topCareer,
            'responses' => $responses,
        ]);
    }
}
