<?php

namespace Core\App\Controllers\Admin;

use PDO;
use Core\System\Csrf;

class ProductReviewController
{
    protected PDO $db;

    public function __construct()
    {
        $this->db = db();
    }

    /* ===============================
       List Reviews
    =============================== */
    public function index(): void
    {
        $stmt = $this->db->query("
            SELECT r.*, p.title AS product_title
            FROM product_reviews r
            INNER JOIN products p ON p.id = r.product_id
            ORDER BY r.created_at DESC
        ");

        $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

        include ROOT_PATH . '/admin/templates/reviews/index.php';
    }

    /* ===============================
       Approve Review
    =============================== */
    public function approve(int $id): void
    {
        Csrf::check();

        $stmt = $this->db->prepare("
            UPDATE product_reviews
            SET status = 'approved'
            WHERE id = ?
        ");
        $stmt->execute([$id]);

        header('Location: /admin/reviews');
        exit;
    }

    /* ===============================
       Delete Review
    =============================== */
    public function delete(int $id): void
    {
        Csrf::check();

        // delete images first
        $this->db->prepare("
            DELETE FROM product_review_images
            WHERE review_id = ?
        ")->execute([$id]);

        // delete review
        $this->db->prepare("
            DELETE FROM product_reviews
            WHERE id = ?
        ")->execute([$id]);

        header('Location: /admin/reviews');
        exit;
    }
}
