<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Testimonial Model
 *
 * Handles student testimonials/reviews data retrieval with JOINs
 * on courses and branches for related names.
 */
class Testimonial extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'testimonials';

    /**
     * Get approved testimonials with JOIN on courses and branches
     * for course name and branch name.
     *
     * @param int $limit Maximum number of testimonials to return
     * @return array<int, array<string, mixed>>
     */
    public function getApproved(int $limit = 6): array
    {
        $sql = sprintf(
            'SELECT t.*, c.name AS course_name, b.name AS branch_name
             FROM `%s` t
             LEFT JOIN `courses` c ON t.course_id = c.id
             LEFT JOIN `branches` b ON t.branch_id = b.id
             WHERE t.is_approved = :is_approved
             ORDER BY t.created_at DESC
             LIMIT :limit',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(':is_approved', 1, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    /**
     * Get the average rating of all approved testimonials.
     *
     * @return float The average rating (0.0 if no testimonials)
     */
    public function getAverageRating(): float
    {
        $sql = sprintf(
            'SELECT AVG(`rating`) AS avg_rating FROM `%s` WHERE `is_approved` = :is_approved',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':is_approved' => 1]);

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        return (float) ($result['avg_rating'] ?? 0.0);
    }
}
