<?php

namespace Core\App\Controllers;

use Core\App\Services\UploadService;
use Core\System\Response;
use PDO;

class ProductReviewController
{
    protected PDO $db;
    protected UploadService $uploads;

    public function __construct()
    {
        $this->db = db();
        $this->uploads = new UploadService(ROOT_PATH . '/uploads', '/uploads');
    }

    public function store(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
            http_response_code(405);
            exit;
        }

        $productId = (int)($_POST['product_id'] ?? 0);
        $name      = trim((string)($_POST['name'] ?? ''));
        $email     = trim((string)($_POST['email'] ?? ''));
        $rating    = (int)($_POST['rating'] ?? 0);
        $comment   = trim((string)($_POST['comment'] ?? ''));

        if (
            $productId <= 0 ||
            $name === '' ||
            !filter_var($email, FILTER_VALIDATE_EMAIL) ||
            $rating < 1 || $rating > 5 ||
            $comment === ''
        ) {
            $_SESSION['review_error'] = __('reviews.invalid_data', 'Invalid review data');
            Response::back('/');
        }

        $stmt = $this->db->prepare("INSERT INTO product_reviews (product_id, name, email, rating, comment, status) VALUES (?, ?, ?, ?, ?, 'pending')");
        $stmt->execute([$productId, $name, $email, $rating, $comment]);
        $reviewId = (int) $this->db->lastInsertId();

        $this->db->prepare("INSERT INTO admin_notifications (type, reference_id, title) VALUES (?, ?, ?)")
            ->execute(['review_pending', $reviewId, __('admin.notification.review_pending', 'Review pending approval')]);

        if (!empty($_FILES['images']['name'][0])) {
            try {
                foreach ($this->uploads->storeImages($_FILES['images'], 'reviews') as $imagePath) {
                    $this->db->prepare("INSERT INTO product_review_images (review_id, image_path) VALUES (?, ?)")
                        ->execute([$reviewId, $imagePath]);
                }
            } catch (\Throwable $e) {
                $_SESSION['review_error'] = __('reviews.invalid_images', 'Some review images were rejected.');
            }
        }

        $_SESSION['review_success'] = __('reviews.thank_you', 'Thank you for your review');
        Response::redirect(Response::sanitizeRedirectTarget((string)($_SERVER['HTTP_REFERER'] ?? '/'), '/') . '#reviews');
    }
}
