<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Testimonial Controller
 *
 * Manage student testimonials with add, approve/reject, and delete functionality.
 * Compatible with both `status` (enum) and `is_approved` (tinyint) column schemas.
 */
class AdminTestimonialController extends AdminController
{
    /**
     * Check which column schema the testimonials table uses.
     * Returns 'status' if the table has a `status` column, 'is_approved' otherwise.
     */
    private function detectSchema(): string
    {
        try {
            $stmt = $this->db->query(
                "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
                 WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'testimonials' AND COLUMN_NAME = 'status'"
            );
            if ($stmt->fetch()) {
                return 'status';
            }
        } catch (\Throwable $e) {}
        return 'is_approved';
    }

    /**
     * List all testimonials.
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $schema = $this->detectSchema();

        if ($schema === 'status') {
            $stmt = $this->db->query(
                'SELECT * FROM `testimonials` ORDER BY FIELD(`status`, "pending") DESC, `created_at` DESC'
            );
        } else {
            $stmt = $this->db->query(
                'SELECT * FROM `testimonials` ORDER BY `is_approved` ASC, `created_at` DESC'
            );
        }
        $testimonials = $stmt->fetchAll() ?: [];

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

    /**
     * Store a new testimonial (created by admin, auto-approved).
     */
    public function store(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $name       = sanitize($_POST['name'] ?? '');
        $courseName = sanitize($_POST['course_name'] ?? '');
        $rating     = (int) ($_POST['rating'] ?? 5);
        $review     = sanitize($_POST['review'] ?? '');

        if (empty($name)) {
            flash('error', 'Student name is required.');
            redirect(BASE_PATH . '/admin/testimonials');
        }

        // Clamp rating between 1 and 5
        if ($rating < 1) $rating = 1;
        if ($rating > 5) $rating = 5;

        // Handle optional photo upload
        $photoPath = $this->handleImageUpload('photo', 'testimonials');

        $schema = $this->detectSchema();

        try {
            if ($schema === 'status') {
                $stmt = $this->db->prepare(
                    'INSERT INTO `testimonials` (`name`, `course_name`, `rating`, `review`, `photo`, `status`)
                     VALUES (:name, :course_name, :rating, :review, :photo, :status)'
                );
                $stmt->execute([
                    ':name'        => $name,
                    ':course_name' => $courseName,
                    ':rating'      => $rating,
                    ':review'      => $review,
                    ':photo'       => $photoPath,
                    ':status'      => 'approved', // Admin-created testimonials are auto-approved
                ]);
            } else {
                $courseId = (int) ($_POST['course_id'] ?? 0);
                $branchId = (int) ($_POST['branch_id'] ?? 0);
                $stmt = $this->db->prepare(
                    'INSERT INTO `testimonials` (`name`, `course_id`, `branch_id`, `rating`, `review`, `photo`, `is_approved`)
                     VALUES (:name, :course_id, :branch_id, :rating, :review, :photo, :is_approved)'
                );
                $stmt->execute([
                    ':name'        => $name,
                    ':course_id'   => $courseId > 0 ? $courseId : null,
                    ':branch_id'   => $branchId > 0 ? $branchId : null,
                    ':rating'      => $rating,
                    ':review'      => $review,
                    ':photo'       => $photoPath,
                    ':is_approved' => 1,
                ]);
            }

            flash('success', 'Testimonial added and auto-approved successfully.');
        } catch (\Throwable $e) {
            error_log('Testimonial create error: ' . $e->getMessage());
            if ($photoPath !== null) {
                $this->deleteImageFile($photoPath);
            }
            flash('error', 'Failed to add testimonial: ' . $e->getMessage());
        }

        redirect(BASE_PATH . '/admin/testimonials');
    }

    /**
     * Approve a pending testimonial.
     */
    public function approve(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);
        $schema = $this->detectSchema();

        if ($schema === 'status') {
            $stmt = $this->db->prepare(
                'UPDATE `testimonials` SET `status` = :status WHERE `id` = :id'
            );
            $stmt->execute([':status' => 'approved', ':id' => $id]);
        } else {
            $stmt = $this->db->prepare(
                'UPDATE `testimonials` SET `is_approved` = 1 WHERE `id` = :id'
            );
            $stmt->execute([':id' => $id]);
        }

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

    /**
     * Reject a testimonial.
     */
    public function reject(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);
        $schema = $this->detectSchema();

        if ($schema === 'status') {
            $stmt = $this->db->prepare(
                'UPDATE `testimonials` SET `status` = :status WHERE `id` = :id'
            );
            $stmt->execute([':status' => 'rejected', ':id' => $id]);
        } else {
            $stmt = $this->db->prepare(
                'UPDATE `testimonials` SET `is_approved` = 0 WHERE `id` = :id'
            );
            $stmt->execute([':id' => $id]);
        }

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

    /**
     * Delete a testimonial.
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

        // Fetch the testimonial to delete its photo
        $stmt = $this->db->prepare('SELECT * FROM `testimonials` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $testimonial = $stmt->fetch() ?: null;

        if ($testimonial !== null) {
            $this->deleteImageFile($testimonial['photo'] ?? null);
        }

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

        if ($stmt->rowCount() > 0) {
            flash('success', 'Testimonial deleted successfully.');
        } else {
            flash('warning', 'Testimonial not found or already deleted.');
        }
        redirect(BASE_PATH . '/admin/testimonials');
    }
}
