<?php
require_once APP_PATH . '/Core/BaseModel.php';

class Mentor extends BaseModel {
    protected string $table = 'mentor_profiles';

    public function search(array $filters = [], int $page = 1): array {
        $where  = ["u.status = 'active'", "mp.verified = 1"];
        $params = [];

        if (!empty($filters['q'])) {
            $q = "%{$filters['q']}%";
            $where[]  = "(u.first_name LIKE ? OR u.last_name LIKE ? OR mp.program LIKE ? OR mp.faculty LIKE ? OR mp.expertise_areas LIKE ?)";
            $params   = array_merge($params, [$q, $q, $q, $q, $q]);
        }
        if (!empty($filters['university_id'])) {
            $where[]  = "mp.university_id = ?";
            $params[] = $filters['university_id'];
        }
        if (!empty($filters['program'])) {
            $where[]  = "mp.program LIKE ?";
            $params[] = "%{$filters['program']}%";
        }
        if (!empty($filters['faculty'])) {
            $where[]  = "mp.faculty LIKE ?";
            $params[] = "%{$filters['faculty']}%";
        }
        if (!empty($filters['career'])) {
            $where[]  = "mp.career_goals LIKE ?";
            $params[] = "%{$filters['career']}%";
        }
        if (isset($filters['available']) && $filters['available']) {
            $where[] = "mp.is_available = 1 AND mp.current_mentees < mp.max_mentees";
        }

        $whereStr = implode(' AND ', $where);
        $offset   = ($page - 1) * ITEMS_PER_PAGE;

        $countStmt = $this->db->prepare(
            "SELECT COUNT(*) FROM mentor_profiles mp
             JOIN users u ON u.id = mp.user_id
             WHERE {$whereStr}"
        );
        $countStmt->execute($params);
        $total = (int) $countStmt->fetchColumn();

        $sql = "SELECT mp.*, u.first_name, u.last_name, u.email, u.avatar,
                       uni.name AS university_name, uni.slug AS university_slug,
                       c.name AS country_name
                FROM mentor_profiles mp
                JOIN users u ON u.id = mp.user_id
                LEFT JOIN universities uni ON uni.id = mp.university_id
                LEFT JOIN countries c ON c.id = mp.country_id
                WHERE {$whereStr}
                ORDER BY mp.rating DESC, mp.sessions_completed DESC
                LIMIT ? OFFSET ?";

        $stmt = $this->db->prepare($sql);
        $stmt->execute([...$params, ITEMS_PER_PAGE, $offset]);

        return [
            'items'        => $stmt->fetchAll(),
            'total'        => $total,
            'per_page'     => ITEMS_PER_PAGE,
            'current_page' => $page,
            'total_pages'  => (int) ceil($total / ITEMS_PER_PAGE),
            'has_prev'     => $page > 1,
            'has_next'     => $page < ceil($total / ITEMS_PER_PAGE),
        ];
    }

    public function getFullProfile(int $mentorId): ?array {
        $profile = $this->fetchOne(
            "SELECT mp.*, u.first_name, u.last_name, u.email, u.phone, u.avatar, u.created_at AS member_since,
                    uni.name AS university_name, uni.slug AS university_slug, uni.logo AS university_logo,
                    c.name AS country_name
             FROM mentor_profiles mp
             JOIN users u ON u.id = mp.user_id
             LEFT JOIN universities uni ON uni.id = mp.university_id
             LEFT JOIN countries c ON c.id = mp.country_id
             WHERE mp.user_id = ?",
            [$mentorId]
        );
        if (!$profile) return null;

        $profile['reviews'] = $this->fetchAll(
            "SELECT mr.*, u.first_name, u.last_name, u.avatar
             FROM mentor_reviews mr
             JOIN users u ON u.id = mr.student_id
             WHERE mr.mentor_id = ?
             ORDER BY mr.created_at DESC LIMIT 5",
            [$mentorId]
        );
        return $profile;
    }

    public function getProfileByUserId(int $userId): ?array {
        return $this->fetchOne(
            "SELECT mp.*, u.first_name, u.last_name, u.email, u.avatar,
                    uni.name AS university_name
             FROM mentor_profiles mp
             JOIN users u ON u.id = mp.user_id
             LEFT JOIN universities uni ON uni.id = mp.university_id
             WHERE mp.user_id = ?",
            [$userId]
        );
    }

    public function hasRequest(int $studentId, int $mentorId): bool {
        return $this->fetchOne(
            "SELECT id FROM mentorship_requests WHERE student_id = ? AND mentor_id = ? AND status IN ('pending','accepted')",
            [$studentId, $mentorId]
        ) !== null;
    }

    public function updateRating(int $mentorId): void {
        $this->execute(
            "UPDATE mentor_profiles mp
             SET rating = (SELECT AVG(rating) FROM mentor_reviews WHERE mentor_id = ?)
             WHERE mp.user_id = ?",
            [$mentorId, $mentorId]
        );
    }

    public function getTopMentors(int $limit = 6): array {
        return $this->fetchAll(
            "SELECT mp.*, u.first_name, u.last_name, u.avatar,
                    uni.name AS university_name
             FROM mentor_profiles mp
             JOIN users u ON u.id = mp.user_id
             LEFT JOIN universities uni ON uni.id = mp.university_id
             WHERE u.status = 'active' AND mp.verified = 1 AND mp.is_available = 1
             ORDER BY mp.rating DESC, mp.sessions_completed DESC
             LIMIT ?",
            [$limit]
        );
    }

    public function incrementMenteeCount(int $userId): void {
        $this->execute(
            "UPDATE mentor_profiles SET current_mentees = current_mentees + 1 WHERE user_id = ?",
            [$userId]
        );
    }
}
