<?php
require_once APP_PATH . '/Core/BaseController.php';
require_once APP_PATH . '/Models/Mentor.php';
require_once APP_PATH . '/Models/Notification.php';
require_once APP_PATH . '/Models/RecommendationEngine.php';
require_once APP_PATH . '/Core/CSRF.php';

class MentorController extends BaseController {

    private Mentor $mentorModel;
    private Notification $notifModel;
    private RecommendationEngine $engine;

    public function __construct() {
        $this->mentorModel = new Mentor();
        $this->notifModel  = new Notification();
        $this->engine      = new RecommendationEngine();
    }

    // ── GET /mentors ─────────────────────────────────────────────
    public function index(): void {
        $page    = max(1, (int)($_GET['page'] ?? 1));
        $filters = [
            'q'             => trim($_GET['q'] ?? ''),
            'university_id' => (int)($_GET['university_id'] ?? 0) ?: null,
            'program'       => trim($_GET['program'] ?? ''),
            'faculty'       => trim($_GET['faculty'] ?? ''),
            'career'        => trim($_GET['career'] ?? ''),
            'available'     => !empty($_GET['available']),
        ];

        $result    = $this->mentorModel->search(array_filter($filters, fn($v) => $v !== null && $v !== ''), $page);
        $db        = Database::getInstance();
        $universities = $db->query("SELECT id, name FROM universities WHERE status='active' ORDER BY name")->fetchAll();

        $this->view('mentors.index', [
            'title'        => 'Mentor Network — BOAFO',
            'mentors'      => $result['items'],
            'pagination'   => $result,
            'filters'      => $filters,
            'universities' => $universities,
        ]);
    }

    // ── GET /mentors/{id} ────────────────────────────────────────
    public function profile(string $id): void {
        $profile = $this->mentorModel->getFullProfile((int) $id);
        if (!$profile) {
            http_response_code(404);
            $this->view('errors.error', ['title'=>'Not Found','code'=>404,'message'=>'Mentor not found.']);
            return;
        }

        $hasRequest = false;
        if (Auth::check() && Auth::isStudent()) {
            $hasRequest = $this->mentorModel->hasRequest(Auth::id(), (int)$id);
        }

        $this->view('mentors.profile', [
            'title'       => $profile['first_name'] . ' ' . $profile['last_name'] . ' — Mentor — BOAFO',
            'mentor'      => $profile,
            'has_request' => $hasRequest,
        ]);
    }

    // ── POST /mentors/{id}/request ───────────────────────────────
    public function sendRequest(string $id): void {
        CSRF::check();

        $mentorId  = (int) $id;
        $studentId = Auth::id();
        $message   = trim($this->input('message', ''));
        $goals     = trim($this->input('goals', ''));

        if ($this->mentorModel->hasRequest($studentId, $mentorId)) {
            if ($this->isAjax()) {
                $this->json(['success'=>false,'message'=>'You have already sent a request to this mentor.']);
            }
            $this->flash('error', 'You have already sent a request to this mentor.');
            $this->back();
        }

        $db = Database::getInstance();
        $stmt = $db->prepare(
            "INSERT INTO mentorship_requests (student_id, mentor_id, message, goals) VALUES (?, ?, ?, ?)"
        );
        $stmt->execute([$studentId, $mentorId, $message, $goals]);

        // Get mentor user info
        $mentor = $db->prepare("SELECT u.* FROM users u JOIN mentor_profiles mp ON mp.user_id = u.id WHERE mp.user_id = ?")->execute([$mentorId]);
        $mentorUser = $db->query("SELECT * FROM users WHERE id = {$mentorId}")->fetch();

        // Send notification to mentor
        $student = Auth::user();
        $this->notifModel->send(
            $mentorId,
            'mentorship_request',
            'New Mentorship Request',
            "{$student['name']} has sent you a mentorship request.",
            APP_URL . '/dashboard'
        );

        if ($this->isAjax()) {
            $this->json(['success'=>true,'message'=>'Mentorship request sent successfully!']);
        }
        $this->flash('success', 'Mentorship request sent successfully!');
        $this->back();
    }

    // ── POST /mentors/requests/{id}/accept ───────────────────────
    public function acceptRequest(string $id): void {
        CSRF::check();
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM mentorship_requests WHERE id = ? AND mentor_id = ? AND status = 'pending'");
        $stmt->execute([(int)$id, Auth::id()]);
        $req = $stmt->fetch();
        if (!$req) {
            $this->flash('error', 'Request not found.');
            $this->back();
        }

        // Accept
        $db->prepare("UPDATE mentorship_requests SET status = 'accepted', responded_at = NOW() WHERE id = ?")->execute([(int)$id]);

        // Create conversation if not exists
        $stmt2 = $db->prepare("SELECT id FROM conversations WHERE student_id = ? AND mentor_id = ?");
        $stmt2->execute([$req['student_id'], $req['mentor_id']]);
        if (!$stmt2->fetch()) {
            $db->prepare("INSERT INTO conversations (student_id, mentor_id) VALUES (?, ?)")->execute([$req['student_id'], $req['mentor_id']]);
        }

        // Notify student
        $notif = new Notification();
        $mentor = Auth::user();
        $notif->send($req['student_id'], 'request_accepted', 'Mentorship Request Accepted', "{$mentor['name']} has accepted your mentorship request. You can now chat with them.", APP_URL . '/messages');

        $this->flash('success', 'Request accepted. You can now chat with the student in the messaging center.');
        $this->back();
    }

    // ── POST /mentors/requests/{id}/decline ──────────────────────
    public function declineRequest(string $id): void {
        CSRF::check();
        $db = Database::getInstance();
        $db->prepare("UPDATE mentorship_requests SET status = 'declined', responded_at = NOW() WHERE id = ? AND mentor_id = ?")->execute([(int)$id, Auth::id()]);
        $this->flash('success', 'Request declined.');
        $this->back();
    }

    // ── GET /mentors/matched ─────────────────────────────────────
    public function matched(): void {
        $matches = $this->engine->matchMentors(Auth::id());
        $this->view('mentors.matched', [
            'title'   => 'Matched Mentors — BOAFO',
            'matches' => $matches,
        ]);
    }

    // ── POST /api/mentors/match ──────────────────────────────────
    public function ajaxMatch(): void {
        CSRF::check();
        $matches = $this->engine->matchMentors(Auth::id());
        $this->json(['success'=>true,'data'=>$matches]);
    }

    // ── GET /api/mentors/search ──────────────────────────────────
    public function ajaxSearch(): void {
        $q = trim($_GET['q'] ?? '');
        $result = $this->mentorModel->search(['q'=>$q,'available'=>true], 1);
        $items = array_map(fn($m) => [
            'id'       => $m['user_id'],
            'name'     => $m['first_name'] . ' ' . $m['last_name'],
            'program'  => $m['program'],
            'university'=> $m['university_name'],
            'avatar'   => avatarUrl($m['avatar'], $m['first_name'] . ' ' . $m['last_name']),
        ], $result['items']);
        $this->json(['results'=>$items]);
    }
}
