<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Testimonial Controller
 *
 * Manage student testimonials with approve/reject functionality.
 */
class AdminTestimonialController extends AdminController
{
    /**
     * List all testimonials with student and course info.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $stmt = $this->db->query(
            'SELECT t.*, c.name AS course_name, b.name AS branch_name
             FROM `testimonials` t
             LEFT JOIN `courses` c ON t.course_id = c.id
             LEFT JOIN `branches` b ON t.branch_id = b.id
             ORDER BY t.is_approved ASC, t.created_at DESC'
        );
        $testimonials = $stmt->fetchAll() ?: [];

        $this->adminView('testimonials', [
            'title'        => 'Manage Testimonials',
            'currentPage'  => 'testimonials',
            'testimonials' => $testimonials,
        ]);
    }

    /**
     * Approve a pending testimonial.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function approve(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare(
            'UPDATE `testimonials` SET `is_approved` = 1 WHERE `id` = :id'
        );
        $stmt->execute([':id' => $id]);

        flash('success', 'Testimonial approved successfully.');
        redirect('/admin/testimonials');
    }

    /**
     * Reject (unapprove) a testimonial.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function reject(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare(
            'UPDATE `testimonials` SET `is_approved` = 0 WHERE `id` = :id'
        );
        $stmt->execute([':id' => $id]);

        flash('success', 'Testimonial rejected.');
        redirect('/admin/testimonials');
    }

    /**
     * Delete a testimonial.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare('DELETE FROM `testimonials` WHERE `id` = :id');
        $stmt->execute([':id' => $id]);

        flash('success', 'Testimonial deleted successfully.');
        redirect('/admin/testimonials');
    }
}
