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

class FavoriteController
{
    private $db;
    private $favorite;

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

    public function toggle()
    {
        $user = AuthMiddleware::authenticate();
        $data = json_decode(file_get_contents("php://input"), true);
        $guesthouse_id = $data['guesthouse_id'] ?? null;

        if (!$guesthouse_id) {
            Response::error("ID da Guest House obrigatório.", 400);
        }

        $result = $this->favorite->toggle($user->id, $guesthouse_id);

        if ($result === "added") {
            Response::success("Adicionado aos favoritos.", ["isFavorite" => true]);
        } elseif ($result === "removed") {
            Response::success("Removido dos favoritos.", ["isFavorite" => false]);
        } else {
            Response::error("Erro ao atualizar favoritos.", 500);
        }
    }

    public function checkFavorite()
    {
        $user = AuthMiddleware::authenticate();
        $guesthouse_id = $_GET['guesthouse_id'] ?? null;

        if (!$guesthouse_id) {
            Response::error("ID da Guest House obrigatório.", 400);
        }

        $isFavorite = $this->favorite->isFavorite($user->id, $guesthouse_id);
        Response::success("Status verificado.", ["isFavorite" => $isFavorite]);
    }

    public function list()
    {
        $user = AuthMiddleware::authenticate();
        $favorites = $this->favorite->getUserFavorites($user->id);

        $formatted_favorites = array();
        foreach ($favorites as $row) {
            $photoUrl = $row['photo_url'];
            if ($photoUrl) {
                $fileName = basename($photoUrl);
                $row['photo_url'] = "https://www.esquinaki.co.mz/uploads/" . $fileName;
            }

            // Format numeric values
            $row['avg_rating'] = $row['avg_rating'] ? (float) $row['avg_rating'] : 0.0;
            $row['reviews_count'] = (int) $row['reviews_count'];

            array_push($formatted_favorites, $row);
        }

        Response::success("Favoritos recuperados.", $formatted_favorites);
    }
}
?>