<?php

namespace App\Controllers;

class ReviewController extends BaseController
{
    public function submitReview()
    {
        $db = \Config\Database::connect();

        $orderId = $this->request->getVar('order_id');
        $productId = $this->request->getVar('product_id');
        $customerId = $this->request->getVar('customer_id');
        $koperasiId = $this->request->getVar('koperasi_id');
        $rating = $this->request->getVar('rating');
        $review = $this->request->getVar('review');

        if (!$orderId || !$productId || !$customerId || !$rating) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Data ulasan tidak lengkap'])->setStatusCode(400);
        }

        // Check if already reviewed
        $existing = $db->table('reviews')
            ->where('order_id', $orderId)
            ->where('product_id', $productId)
            ->get()->getRow();

        if ($existing) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Produk ini sudah diulas untuk pesanan ini'])->setStatusCode(400);
        }

        $db->transStart();

        // 1. Insert Review
        $db->table('reviews')->insert([
            'order_id' => $orderId,
            'product_id' => $productId,
            'customer_id' => $customerId,
            'koperasi_id' => $koperasiId ?: 0,
            'rating' => $rating,
            'review' => $review,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        // 2. Update is_reviewed in order_items
        $db->table('order_items')
            ->where('order_id', $orderId)
            ->where('product_id', $productId)
            ->update(['is_reviewed' => 1]);

        // 3. Recalculate average rating for the product
        $avgQuery = $db->table('reviews')
            ->select('AVG(rating) as avg_rating')
            ->where('product_id', $productId)
            ->get()->getRow();

        $newRating = $avgQuery ? round($avgQuery->avg_rating, 2) : 5.00;

        // 4. Update products table
        $db->table('products')
            ->where('id', $productId)
            ->update(['rating' => $newRating]);

        $db->transComplete();

        if ($db->transStatus() === FALSE) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Gagal menyimpan ulasan'])->setStatusCode(500);
        }

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Ulasan berhasil disimpan',
            'new_rating' => $newRating
        ]);
    }

    public function getProductReviews($productId)
    {
        $db = \Config\Database::connect();
        
        $reviews = $db->table('reviews r')
            ->select('r.*, u.nama as customer_name')
            ->join('users u', 'u.id = r.customer_id')
            ->where('r.product_id', $productId)
            ->orderBy('r.created_at', 'DESC')
            ->get()
            ->getResultArray();

        return $this->response->setJSON([
            'status' => 'success',
            'data' => $reviews
        ]);
    }
}
