<?php

require_once BASE_PATH
    . '/app/controllers/owner/OwnerBaseController.php';

require_once BASE_PATH
    . '/app/models/GalleryItem.php';


class OwnerGalleryController
    extends OwnerBaseController
{
    private GalleryItem $galleryModel;

    public function __construct()
    {
        $this->requireOwner();

        $this->galleryModel =
            new GalleryItem();
    }

    public function index(): void
    {
        $search =
            trim(
                $_GET['search'] ?? ''
            );

        $page =
            max(
                1,
                (int)
                ($_GET['page'] ?? 1)
            );

        $perPage = 20;

        $totalItems =
            $this->galleryModel
                ->countForOwner(
                    $search
                );

        $totalPages =
            max(
                1,
                (int)
                ceil(
                    $totalItems
                    / $perPage
                )
            );

        $page =
            min(
                $page,
                $totalPages
            );

        $galleryItems =
            $this->galleryModel
                ->getForOwner(
                    $search,
                    $perPage,
                    ($page - 1)
                    * $perPage
                );

        require BASE_PATH
            . '/app/views/owner/gallery/index.php';
    }

    public function store(): void
    {
        $this->requirePost();
        $this->validateCsrf();

        try {

            $imagePath =
                $this->uploadImage();

            $this->galleryModel
                ->create([
                    'title' =>
                        trim(
                            $_POST['title'] ?? ''
                        ),

                    'caption' =>
                        trim(
                            $_POST['caption'] ?? ''
                        ),

                    'category' =>
                        trim(
                            $_POST['category'] ?? ''
                        ),

                    'image_path' =>
                        $imagePath,

                    'sort_order' =>
                        (int)
                        ($_POST['sort_order'] ?? 0),

                    'is_visible' =>
                        isset(
                            $_POST['is_visible']
                        )
                        ? 1
                        : 0
                ]);

            $this->flashSuccess(
                'Đã thêm ảnh vào Gallery.'
            );

        } catch (RuntimeException $e) {

            $this->flashError(
                $e->getMessage()
            );
        }

        $this->redirect(
            'owner/gallery'
        );
    }

    public function edit(): void
    {
        $id =
            (int)
            ($_GET['id'] ?? 0);

        $item =
            $this->galleryModel
                ->findById($id);

        if (!$item) {

            http_response_code(404);

            require BASE_PATH
                . '/app/views/errors/404.php';

            return;
        }

        require BASE_PATH
            . '/app/views/owner/gallery/edit.php';
    }

    public function update(): void
    {
        $this->requirePost();
        $this->validateCsrf();

        $id =
            (int)
            ($_POST['gallery_id'] ?? 0);

        $item =
            $this->galleryModel
                ->findById($id);

        if (!$item) {

            $this->flashError(
                'Ảnh không tồn tại.'
            );

            $this->redirect(
                'owner/gallery'
            );
        }

        $this->galleryModel
            ->updateItem(
                $id,
                [
                    'title' =>
                        trim(
                            $_POST['title'] ?? ''
                        ),

                    'caption' =>
                        trim(
                            $_POST['caption'] ?? ''
                        ),

                    'category' =>
                        trim(
                            $_POST['category'] ?? ''
                        ),

                    'sort_order' =>
                        (int)
                        ($_POST['sort_order'] ?? 0),

                    'is_visible' =>
                        isset(
                            $_POST['is_visible']
                        )
                        ? 1
                        : 0
                ]
            );

        $this->flashSuccess(
            'Đã cập nhật ảnh.'
        );

        header(
            'Location: '
            . BASE_URL
            . '/?url=owner/gallery/edit&id='
            . $id
        );

        exit;
    }

    public function toggle(): void
    {
        $this->requirePost();
        $this->validateCsrf();

        $id =
            (int)
            ($_POST['gallery_id'] ?? 0);

        $this->galleryModel
            ->toggle($id);

        $this->flashSuccess(
            'Đã cập nhật trạng thái ảnh.'
        );

        $this->redirect(
            'owner/gallery'
        );
    }

    public function delete(): void
    {
        $this->requirePost();
        $this->validateCsrf();

        $id =
            (int)
            ($_POST['gallery_id'] ?? 0);

        $item =
            $this->galleryModel
                ->findById($id);

        if ($item) {

            $file =
                BASE_PATH
                . '/public/'
                . ltrim(
                    $item['image_path'],
                    '/'
                );

            if (is_file($file)) {
                @unlink($file);
            }

            $this->galleryModel
                ->delete($id);
        }

        $this->flashSuccess(
            'Đã xóa ảnh khỏi Gallery.'
        );

        $this->redirect(
            'owner/gallery'
        );
    }

    private function uploadImage(): string
    {
        if (
            empty(
                $_FILES['image']
            )

            || $_FILES[
                'image'
            ]['error']
            === UPLOAD_ERR_NO_FILE
        ) {

            throw new RuntimeException(
                'Vui lòng chọn hình ảnh.'
            );
        }

        $file =
            $_FILES['image'];

        if (
            $file['error']
            !== UPLOAD_ERR_OK
        ) {

            throw new RuntimeException(
                'Upload hình ảnh thất bại.'
            );
        }

        if (
            $file['size']
            > 5 * 1024 * 1024
        ) {

            throw new RuntimeException(
                'Ảnh tối đa 5MB.'
            );
        }

        $finfo =
            new finfo(
                FILEINFO_MIME_TYPE
            );

        $mime =
            $finfo->file(
                $file['tmp_name']
            );

        $allowed = [
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/webp' => 'webp'
        ];

        if (
            !isset(
                $allowed[$mime]
            )
        ) {

            throw new RuntimeException(
                'Chỉ hỗ trợ JPG, PNG hoặc WEBP.'
            );
        }

        $directory =
            BASE_PATH
            . '/public/uploads/gallery/';

        if (!is_dir($directory)) {

            mkdir(
                $directory,
                0755,
                true
            );
        }

        $filename =
            'gallery_'
            . bin2hex(
                random_bytes(10)
            )
            . '.'
            . $allowed[$mime];

        if (
            !move_uploaded_file(
                $file['tmp_name'],
                $directory . $filename
            )
        ) {

            throw new RuntimeException(
                'Không thể lưu ảnh.'
            );
        }

        return 'uploads/gallery/'
            . $filename;
    }
}