<?php
require_once __DIR__ . '/../models/Review.php';
require_once __DIR__ . '/../helpers/Response.php';
require_once __DIR__ . '/../middlewares/AuthMiddleware.php';
require_once __DIR__ . '/../helpers/Validator.php';

class ReviewController
{
    private $db;
    private $review;

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

    public function create()
    {
        try {
            $user = AuthMiddleware::authenticate();

            $input = file_get_contents("php://input");
            $data = json_decode($input, true);

            if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
                Response::error("Invalid JSON data provided.", 400);
                return;
            }

            $rules = [
                'guesthouse_id' => 'required',
                'rating' => 'required'
            ];

            $errors = Validator::validate($data, $rules);

            if (!empty($errors)) {
                Response::error("Validation Error", 400, $errors);
                return;
            }

            $this->review->user_id = $user->id;
            $this->review->guesthouse_id = $data['guesthouse_id'];
            $this->review->booking_id = $data['booking_id'] ?? null;
            $this->review->rating = $data['rating'];
            $this->review->comment = $data['comment'] ?? '';

            if ($this->review->create()) {
                Response::success("Review created successfully.");
            } else {
                Response::error("Unable to create review.", 503);
            }
        } catch (Exception $e) {
            Response::error("An unexpected error occurred: " . $e->getMessage(), 500);
        }
    }

    public function list()
    {
        if (!isset($_GET['guesthouse_id'])) {
            Response::error("Guesthouse ID is required.", 400);
            return;
        }

        $stmt = $this->review->getByGuesthouseId($_GET['guesthouse_id']);
        $num = $stmt->rowCount();

        if ($num >= 0) {
            $reviews_arr = array();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                array_push($reviews_arr, $row);
            }
            Response::success("Reviews found.", $reviews_arr);
        } else {
            Response::success("No reviews found.", []);
        }
    }
}
?>