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

class PhotoController
{
    private $db;
    private $photo;

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

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

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (isset($_FILES['photo']) && isset($_POST['guesthouse_id'])) {

                $uploadResult = FileUpload::upload($_FILES['photo']);

                if ($uploadResult['success']) {
                    $this->photo->guesthouse_id = $_POST['guesthouse_id'];
                    // Construct correct URL: replace /api/ with /uploads/ in BASE_URL
                    // and append only the filename, not the full path
                    $fileName = basename($uploadResult['filePath']);
                    $uploadsUrl = str_replace('/api/', '/uploads/', BASE_URL);
                    $this->photo->photo_url = $uploadsUrl . $fileName;

                    $this->photo->is_main = isset($_POST['is_main']) ? $_POST['is_main'] : 0;

                    // If replacing main photo, delete previous ones for this guesthouse
                    if ($this->photo->is_main == 1) {
                        $this->photo->deleteByGuesthouseId($this->photo->guesthouse_id);
                    }

                    if ($this->photo->create()) {
                        Response::success("Photo uploaded successfully.", ["url" => $this->photo->photo_url]);
                    } else {
                        Response::error("Database insertion failed.", 503);
                    }
                } else {
                    Response::error($uploadResult['message'], 400);
                }
            } else {
                Response::error("Missing photo or guesthouse_id.", 400);
            }
        } else {
            Response::error("Invalid request method.", 405);
        }
    }

    public function listByGuesthouse()
    {
        if (isset($_GET['guesthouse_id'])) {
            $stmt = $this->photo->getByGuesthouseId($_GET['guesthouse_id']);
            $num = $stmt->rowCount();

            if ($num >= 0) {
                $photos_arr = array();
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $photoUrl = $row['photo_url'];
                    if ($photoUrl) {
                        $fileName = basename($photoUrl);
                        $row['photo_url'] = "https://www.esquinaki.co.mz/uploads/" . $fileName;
                    }
                    array_push($photos_arr, $row);
                }
                Response::success("Photos found.", $photos_arr);
            } else {
                Response::success("No photos found.", []);
            }
        } else {
            Response::error("Missing guesthouse_id.", 400);
        }
    }

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

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

        $photoData = $this->photo->findById($id);
        if (!$photoData) {
            Response::error("Foto não encontrada.", 404);
        }

        // Optional: Check if the user owns the guesthouse before deleting the photo
        // For now, we trust the authenticating user (but a real app would check guesthouse ownership)

        if ($this->photo->delete($id)) {
            // Delete file from disk
            $photoUrl = $photoData['photo_url'];
            $fileName = basename($photoUrl);
            $filePath = __DIR__ . '/../../uploads/' . $fileName;
            if (file_exists($filePath)) {
                unlink($filePath);
            }
            Response::success("Foto eliminada com sucesso.");
        } else {
            Response::error("Erro ao eliminar foto da base de dados.", 500);
        }
    }
}
?>