<?php

$pageTitle =
    'Chỉnh sửa sản phẩm - PET SPA';

$pageStyles = [
    'owner.css'
];

$activeOwnerPage =
    'products';


// ============================================================
// FLASH MESSAGE
// ============================================================

$successMessage =
    $_SESSION['flash_success']
    ?? null;

$errorMessage =
    $_SESSION['flash_error']
    ?? null;


unset(
    $_SESSION['flash_success'],
    $_SESSION['flash_error']
);


// ============================================================
// LOAD LAYOUT
// ============================================================

require BASE_PATH
    . '/app/views/layouts/header.php';

require BASE_PATH
    . '/app/views/layouts/navbar.php';

?>


<main class="owner-area">

    <div class="container-fluid">

        <div class="row g-4">


            <!-- ==================================================
                 SIDEBAR
            =================================================== -->

            <div class="col-xl-2 col-lg-3">

                <?php

                require BASE_PATH
                    . '/app/views/layouts/owner-sidebar.php';

                ?>

            </div>


            <!-- ==================================================
                 MAIN CONTENT
            =================================================== -->

            <div class="col-xl-10 col-lg-9">


                <!-- HEADER -->

                <div class="owner-page-header">

                    <div>

                        <a
                            href="<?= BASE_URL ?>/?url=owner/products"
                            class="small text-decoration-none"
                        >
                            ← Quay lại sản phẩm
                        </a>


                        <h1 class="mt-2">
                            Chỉnh sửa sản phẩm
                        </h1>


                        <p>

                            <?= htmlspecialchars(
                                $product['name']
                            ) ?>

                        </p>

                    </div>


                    <!-- XEM NGOÀI SHOP -->

                    <?php if (
                        $product['status']
                        !== 'hidden'
                    ): ?>

                        <a
                            href="<?= BASE_URL ?>/?url=product&slug=<?= urlencode(
                                $product['slug']
                            ) ?>"
                            target="_blank"
                            class="btn btn-outline-dark"
                        >

                            <i
                                class="bi bi-box-arrow-up-right me-1"
                            ></i>

                            Xem ngoài Shop

                        </a>

                    <?php endif; ?>

                </div>


                <!-- ==================================================
                     FLASH SUCCESS
                =================================================== -->

                <?php if ($successMessage): ?>

                    <div
                        class="alert alert-success alert-dismissible fade show"
                    >

                        <i
                            class="bi bi-check-circle me-2"
                        ></i>


                        <?= htmlspecialchars(
                            $successMessage
                        ) ?>


                        <button
                            type="button"
                            class="btn-close"
                            data-bs-dismiss="alert"
                        ></button>

                    </div>

                <?php endif; ?>


                <!-- ==================================================
                     FLASH ERROR
                =================================================== -->

                <?php if ($errorMessage): ?>

                    <div
                        class="alert alert-danger alert-dismissible fade show"
                    >

                        <i
                            class="bi bi-exclamation-circle me-2"
                        ></i>


                        <?= htmlspecialchars(
                            $errorMessage
                        ) ?>


                        <button
                            type="button"
                            class="btn-close"
                            data-bs-dismiss="alert"
                        ></button>

                    </div>

                <?php endif; ?>


                <!-- ==================================================
                     UPDATE PRODUCT FORM
                =================================================== -->

                <form
                    action="<?= BASE_URL ?>/?url=owner/product/update"
                    method="POST"
                    enctype="multipart/form-data"
                >


                    <!-- CSRF -->

                    <input
                        type="hidden"
                        name="_token"
                        value="<?= htmlspecialchars(
                            $_SESSION['csrf_token']
                        ) ?>"
                    >


                    <!-- PRODUCT ID -->

                    <input
                        type="hidden"
                        name="product_id"
                        value="<?= (int)
                            $product['id']
                        ?>"
                    >


                    <div class="row g-4">


                        <!-- ==================================================
                             LEFT COLUMN
                        =================================================== -->

                        <div class="col-xl-8">


                            <!-- ==============================================
                                 PRODUCT INFORMATION
                            =============================================== -->

                            <section class="owner-card">

                                <h2>
                                    Thông tin sản phẩm
                                </h2>


                                <div class="row g-3">


                                    <!-- NAME -->

                                    <div class="col-12">

                                        <label
                                            class="form-label fw-semibold"
                                        >
                                            Tên sản phẩm
                                            <span class="text-danger">*</span>
                                        </label>


                                        <input
                                            type="text"
                                            name="name"
                                            class="form-control"
                                            maxlength="200"
                                            value="<?= htmlspecialchars(
                                                $product['name']
                                            ) ?>"
                                            required
                                        >

                                    </div>


                                    <!-- SKU -->

                                    <div class="col-md-6">

                                        <label
                                            class="form-label fw-semibold"
                                        >
                                            SKU
                                        </label>


                                        <input
                                            type="text"
                                            name="sku"
                                            class="form-control"
                                            maxlength="80"
                                            value="<?= htmlspecialchars(
                                                $product['sku']
                                                ?? ''
                                            ) ?>"
                                            placeholder="Ví dụ: RC001"
                                        >


                                        <small class="text-muted">
                                            Mã sản phẩm không được trùng.
                                        </small>

                                    </div>


                                    <!-- BRAND -->

                                    <div class="col-md-6">

                                        <label
                                            class="form-label fw-semibold"
                                        >
                                            Thương hiệu
                                        </label>


                                        <input
                                            type="text"
                                            name="brand"
                                            class="form-control"
                                            maxlength="120"
                                            value="<?= htmlspecialchars(
                                                $product['brand']
                                                ?? ''
                                            ) ?>"
                                            placeholder="Ví dụ: Royal Canin"
                                        >

                                    </div>


                                    <!-- CURRENT SLUG -->

                                    <div class="col-12">

                                        <label
                                            class="form-label fw-semibold"
                                        >
                                            Đường dẫn hiện tại
                                        </label>


                                        <div class="input-group">

                                            <span
                                                class="input-group-text"
                                            >
                                                /product/
                                            </span>


                                            <input
                                                type="text"
                                                class="form-control"
                                                value="<?= htmlspecialchars(
                                                    $product['slug']
                                                ) ?>"
                                                readonly
                                            >

                                        </div>


                                        <small class="text-muted">

                                            Slug sẽ được hệ thống tạo lại
                                            tự động theo tên sản phẩm khi lưu.

                                        </small>

                                    </div>


                                    <!-- SHORT DESCRIPTION -->

                                    <div class="col-12">

                                        <label
                                            class="form-label fw-semibold"
                                        >
                                            Mô tả ngắn
                                        </label>


                                        <textarea
                                            name="short_description"
                                            class="form-control"
                                            rows="3"
                                            maxlength="500"
                                            placeholder="Mô tả ngắn xuất hiện ở phần giới thiệu sản phẩm..."
                                        ><?= htmlspecialchars(
                                            $product[
                                                'short_description'
                                            ]
                                            ?? ''
                                        ) ?></textarea>

                                    </div>


                                    <!-- DESCRIPTION -->

                                    <div class="col-12">

                                        <label
                                            class="form-label fw-semibold"
                                        >
                                            Mô tả chi tiết
                                        </label>


                                        <textarea
                                            name="description"
                                            class="form-control"
                                            rows="12"
                                            placeholder="Nhập thông tin chi tiết sản phẩm..."
                                        ><?= htmlspecialchars(
                                            $product['description']
                                            ?? ''
                                        ) ?></textarea>

                                    </div>

                                </div>

                            </section>


                            <!-- ==============================================
                                 PRODUCT IMAGES
                            =============================================== -->

                            <section class="owner-card mt-4">

                                <div class="owner-card-header">

                                    <div>

                                        <h2 class="mb-1">
                                            Hình ảnh sản phẩm
                                        </h2>


                                        <p
                                            class="text-muted small mb-0"
                                        >
                                            JPG, PNG hoặc WEBP.
                                            Mỗi ảnh tối đa 5MB.
                                        </p>

                                    </div>

                                </div>


                                <!-- CURRENT FEATURED IMAGE -->

                                <?php if (
                                    !empty(
                                        $product[
                                            'featured_image'
                                        ]
                                    )
                                ): ?>

                                    <div class="mb-4">

                                        <label
                                            class="form-label fw-semibold"
                                        >
                                            Ảnh đại diện hiện tại
                                        </label>


                                        <div
                                            class="owner-current-featured-image"
                                        >

                                            <img
                                                src="<?= BASE_URL ?>/<?= htmlspecialchars(
                                                    ltrim(
                                                        $product[
                                                            'featured_image'
                                                        ],
                                                        '/'
                                                    )
                                                ) ?>"
                                                alt="<?= htmlspecialchars(
                                                    $product['name']
                                                ) ?>"
                                            >

                                        </div>

                                    </div>

                                <?php endif; ?>


                                <!-- UPLOAD NEW IMAGES -->

                                <div class="mb-3">

                                    <label
                                        class="form-label fw-semibold"
                                    >
                                        Thêm hình ảnh mới
                                    </label>


                                    <input
                                        type="file"
                                        name="product_images[]"
                                        id="productImages"
                                        class="form-control"
                                        accept="image/jpeg,image/png,image/webp"
                                        multiple
                                    >

                                </div>


                                <!-- IMAGE PREVIEW -->

                                <div
                                    id="imagePreview"
                                    class="owner-product-gallery mt-3"
                                ></div>


                                <!-- EXISTING IMAGES -->

                                <?php if (
                                    !empty(
                                        $productImages
                                    )
                                ): ?>

                                    <hr class="my-4">


                                    <h3 class="h6 fw-bold mb-3">
                                        Thư viện hiện tại
                                    </h3>


                                    <div
                                        class="owner-product-gallery"
                                    >

                                        <?php foreach (
                                            $productImages
                                            as $image
                                        ): ?>


                                            <?php

                                            $isFeatured =
                                                !empty(
                                                    $product[
                                                        'featured_image'
                                                    ]
                                                )

                                                && $product[
                                                    'featured_image'
                                                ]
                                                === $image[
                                                    'image_path'
                                                ];

                                            ?>


                                            <div
                                                class="owner-product-gallery-item"
                                            >


                                                <img
                                                    src="<?= BASE_URL ?>/<?= htmlspecialchars(
                                                        ltrim(
                                                            $image[
                                                                'image_path'
                                                            ],
                                                            '/'
                                                        )
                                                    ) ?>"
                                                    alt=""
                                                >


                                                <?php if ($isFeatured): ?>

                                                    <span
                                                        class="position-absolute bottom-0 start-0 m-2 badge bg-primary"
                                                    >
                                                        Ảnh đại diện
                                                    </span>

                                                <?php endif; ?>


                                                <!-- DELETE IMAGE -->

                                                <button
                                                    type="submit"
                                                    form="delete-image-<?= (int)
                                                        $image['id']
                                                    ?>"
                                                    class="btn btn-danger btn-sm"
                                                    title="Xóa ảnh"
                                                >
                                                    <i
                                                        class="bi bi-trash"
                                                    ></i>
                                                </button>

                                            </div>

                                        <?php endforeach; ?>

                                    </div>

                                <?php else: ?>

                                    <div
                                        class="alert alert-light border mt-4 mb-0"
                                    >

                                        <i
                                            class="bi bi-images me-2"
                                        ></i>

                                        Sản phẩm chưa có thư viện ảnh.

                                    </div>

                                <?php endif; ?>

                            </section>

                        </div>


                        <!-- ==================================================
                             RIGHT COLUMN
                        =================================================== -->

                        <div class="col-xl-4">


                            <!-- ==============================================
                                 CATEGORY
                            =============================================== -->

                            <section class="owner-card">

                                <h2>
                                    Phân loại
                                </h2>


                                <!-- CATEGORY -->

                                <div class="mb-3">

                                    <label
                                        class="form-label fw-semibold"
                                    >
                                        Danh mục
                                        <span class="text-danger">*</span>
                                    </label>


                                    <select
                                        name="category_id"
                                        class="form-select"
                                        required
                                    >

                                        <option value="">
                                            Chọn danh mục
                                        </option>


                                        <?php foreach (
                                            $categories
                                            as $category
                                        ): ?>

                                            <option
                                                value="<?= (int)
                                                    $category['id']
                                                ?>"

                                                <?= (int)
                                                    $product[
                                                        'category_id'
                                                    ]
                                                    === (int)
                                                    $category['id']
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >

                                                <?= htmlspecialchars(
                                                    $category['name']
                                                ) ?>

                                            </option>

                                        <?php endforeach; ?>

                                    </select>

                                </div>


                                <!-- PET TARGET -->

                                <div class="mb-0">

                                    <label
                                        class="form-label fw-semibold"
                                    >
                                        Dành cho
                                    </label>


                                    <select
                                        name="pet_target"
                                        class="form-select"
                                    >

                                        <option
                                            value="all"
                                            <?= $product[
                                                'pet_target'
                                            ] === 'all'
                                                ? 'selected'
                                                : ''
                                            ?>
                                        >
                                            🐶🐱 Chó & Mèo
                                        </option>


                                        <option
                                            value="dog"
                                            <?= $product[
                                                'pet_target'
                                            ] === 'dog'
                                                ? 'selected'
                                                : ''
                                            ?>
                                        >
                                            🐶 Chó
                                        </option>


                                        <option
                                            value="cat"
                                            <?= $product[
                                                'pet_target'
                                            ] === 'cat'
                                                ? 'selected'
                                                : ''
                                            ?>
                                        >
                                            🐱 Mèo
                                        </option>

                                    </select>

                                </div>

                            </section>


                            <!-- ==============================================
                                 PRICE
                            =============================================== -->

                            <section class="owner-card mt-4">

                                <h2>
                                    Giá bán
                                </h2>


                                <!-- ORIGINAL PRICE -->

                                <div class="mb-3">

                                    <label
                                        class="form-label fw-semibold"
                                    >
                                        Giá gốc
                                        <span class="text-danger">*</span>
                                    </label>


                                    <div class="input-group">

                                        <input
                                            type="number"
                                            name="price"
                                            class="form-control"
                                            min="1"
                                            step="1000"
                                            value="<?= (float)
                                                $product['price']
                                            ?>"
                                            required
                                        >

                                        <span
                                            class="input-group-text"
                                        >
                                            VNĐ
                                        </span>

                                    </div>

                                </div>


                                <!-- SALE PRICE -->

                                <div class="mb-0">

                                    <label
                                        class="form-label fw-semibold"
                                    >
                                        Giá khuyến mãi
                                    </label>


                                    <div class="input-group">

                                        <input
                                            type="number"
                                            name="sale_price"
                                            class="form-control"
                                            min="0"
                                            step="1000"
                                            value="<?= htmlspecialchars(
                                                $product[
                                                    'sale_price'
                                                ]
                                                ?? ''
                                            ) ?>"
                                            placeholder="Không giảm giá"
                                        >

                                        <span
                                            class="input-group-text"
                                        >
                                            VNĐ
                                        </span>

                                    </div>


                                    <small class="text-muted">

                                        Để trống nếu không giảm giá.

                                    </small>

                                </div>

                            </section>


                            <!-- ==============================================
                                 STOCK
                            =============================================== -->

                            <section class="owner-card mt-4">

                                <h2>
                                    Kho hàng
                                </h2>


                                <!-- STOCK -->

                                <div class="mb-3">

                                    <label
                                        class="form-label fw-semibold"
                                    >
                                        Số lượng tồn kho
                                    </label>


                                    <input
                                        type="number"
                                        name="stock_quantity"
                                        class="form-control"
                                        min="0"
                                        value="<?= (int)
                                            $product[
                                                'stock_quantity'
                                            ]
                                        ?>"
                                    >

                                </div>


                                <!-- SOLD QUANTITY -->

                                <div>

                                    <label
                                        class="form-label fw-semibold"
                                    >
                                        Đã bán
                                    </label>


                                    <input
                                        type="text"
                                        class="form-control"
                                        value="<?= (int)
                                            $product[
                                                'sold_quantity'
                                            ]
                                        ?> sản phẩm"
                                        readonly
                                    >


                                    <small class="text-muted">

                                        Số lượng đã bán được hệ thống
                                        tự động cập nhật.

                                    </small>

                                </div>

                            </section>


                            <!-- ==============================================
                                 DISPLAY
                            =============================================== -->

                            <section class="owner-card mt-4">

                                <h2>
                                    Hiển thị
                                </h2>


                                <!-- STATUS -->

                                <div class="mb-3">

                                    <label
                                        class="form-label fw-semibold"
                                    >
                                        Trạng thái
                                    </label>


                                    <select
                                        name="status"
                                        class="form-select"
                                    >

                                        <option
                                            value="active"

                                            <?= $product['status']
                                                === 'active'
                                                ? 'selected'
                                                : ''
                                            ?>
                                        >
                                            Đang bán
                                        </option>


                                        <option
                                            value="out_of_stock"

                                            <?= $product['status']
                                                === 'out_of_stock'
                                                ? 'selected'
                                                : ''
                                            ?>
                                        >
                                            Hết hàng
                                        </option>


                                        <option
                                            value="hidden"

                                            <?= $product['status']
                                                === 'hidden'
                                                ? 'selected'
                                                : ''
                                            ?>
                                        >
                                            Ẩn sản phẩm
                                        </option>

                                    </select>


                                    <?php if (
                                        (int)
                                        $product[
                                            'stock_quantity'
                                        ]
                                        === 0
                                    ): ?>

                                        <small class="text-warning">

                                            <i
                                                class="bi bi-exclamation-triangle me-1"
                                            ></i>

                                            Tồn kho đang bằng 0 nên
                                            hệ thống sẽ chuyển sản phẩm
                                            sang trạng thái hết hàng.

                                        </small>

                                    <?php endif; ?>

                                </div>


                                <!-- FEATURED -->

                                <div class="form-check">

                                    <input
                                        type="checkbox"
                                        name="is_featured"
                                        class="form-check-input"
                                        id="isFeatured"

                                        <?= (int)
                                            $product[
                                                'is_featured'
                                            ]
                                            === 1
                                            ? 'checked'
                                            : ''
                                        ?>
                                    >


                                    <label
                                        class="form-check-label"
                                        for="isFeatured"
                                    >
                                        Hiển thị ở sản phẩm nổi bật
                                    </label>

                                </div>

                            </section>


                            <!-- ==============================================
                                 PRODUCT INFO
                            =============================================== -->

                            <section class="owner-card mt-4">

                                <h2>
                                    Thông tin hệ thống
                                </h2>


                                <div class="small">

                                    <div
                                        class="d-flex justify-content-between gap-3 mb-2"
                                    >

                                        <span class="text-muted">
                                            ID
                                        </span>

                                        <strong>

                                            #<?= (int)
                                                $product['id']
                                            ?>

                                        </strong>

                                    </div>


                                    <div
                                        class="d-flex justify-content-between gap-3 mb-2"
                                    >

                                        <span class="text-muted">
                                            Ngày tạo
                                        </span>

                                        <strong>

                                            <?= date(
                                                'd/m/Y H:i',
                                                strtotime(
                                                    $product[
                                                        'created_at'
                                                    ]
                                                )
                                            ) ?>

                                        </strong>

                                    </div>


                                    <div
                                        class="d-flex justify-content-between gap-3"
                                    >

                                        <span class="text-muted">
                                            Cập nhật
                                        </span>

                                        <strong>

                                            <?= date(
                                                'd/m/Y H:i',
                                                strtotime(
                                                    $product[
                                                        'updated_at'
                                                    ]
                                                )
                                            ) ?>

                                        </strong>

                                    </div>

                                </div>

                            </section>


                            <!-- ==============================================
                                 SAVE BUTTON
                            =============================================== -->

                            <div
                                class="d-grid gap-2 mt-4"
                            >

                                <button
                                    type="submit"
                                    class="btn btn-primary btn-lg"
                                >

                                    <i
                                        class="bi bi-check-lg me-1"
                                    ></i>

                                    Lưu thay đổi

                                </button>


                                <a
                                    href="<?= BASE_URL ?>/?url=owner/products"
                                    class="btn btn-light"
                                >
                                    Hủy
                                </a>

                            </div>

                        </div>

                    </div>

                </form>


                <?php foreach ($productImages as $image): ?>

                    <form
                        id="delete-image-<?= (int) $image['id'] ?>"
                        class="d-none"
                        action="<?= BASE_URL ?>/?url=owner/product/image/delete"
                        method="POST"
                        onsubmit="return confirm('Bạn chắc chắn muốn xóa ảnh này?')"
                    >

                        <input
                            type="hidden"
                            name="_token"
                            value="<?= htmlspecialchars(
                                $_SESSION['csrf_token']
                            ) ?>"
                        >

                        <input
                            type="hidden"
                            name="product_id"
                            value="<?= (int) $product['id'] ?>"
                        >

                        <input
                            type="hidden"
                            name="image_id"
                            value="<?= (int) $image['id'] ?>"
                        >

                    </form>

                <?php endforeach; ?>


                <!-- ==================================================
                     HIDE PRODUCT
                     Nằm ngoài form update để tránh form lồng nhau
                =================================================== -->

                <?php if (
                    $product['status']
                    !== 'hidden'
                ): ?>

                    <section
                        class="owner-card mt-4 border-danger"
                    >

                        <h2 class="text-danger">
                            Ẩn sản phẩm
                        </h2>


                        <p class="text-muted">

                            Sản phẩm sẽ không còn hiển thị
                            cho khách hàng nhưng dữ liệu đơn hàng
                            và lịch sử bán hàng vẫn được giữ lại.

                        </p>


                        <form
                            action="<?= BASE_URL ?>/?url=owner/product/hide"
                            method="POST"
                            onsubmit="return confirm('Bạn chắc chắn muốn ẩn sản phẩm này?')"
                        >

                            <input
                                type="hidden"
                                name="_token"
                                value="<?= htmlspecialchars(
                                    $_SESSION[
                                        'csrf_token'
                                    ]
                                ) ?>"
                            >


                            <input
                                type="hidden"
                                name="product_id"
                                value="<?= (int)
                                    $product['id']
                                ?>"
                            >


                            <button
                                type="submit"
                                class="btn btn-outline-danger"
                            >

                                <i
                                    class="bi bi-eye-slash me-1"
                                ></i>

                                Ẩn sản phẩm

                            </button>

                        </form>

                    </section>

                <?php endif; ?>

            </div>

        </div>

    </div>

</main>


<!-- ============================================================
     IMAGE PREVIEW
============================================================= -->

<script>

document.addEventListener(
    'DOMContentLoaded',
    function () {

        const input =
            document.getElementById(
                'productImages'
            );

        const preview =
            document.getElementById(
                'imagePreview'
            );


        if (!input || !preview) {
            return;
        }


        input.addEventListener(
            'change',
            function () {

                preview.innerHTML = '';


                const files =
                    Array.from(
                        this.files
                    );


                files.forEach(
                    function (file) {

                        if (
                            !file.type.startsWith(
                                'image/'
                            )
                        ) {
                            return;
                        }


                        const reader =
                            new FileReader();


                        reader.onload =
                            function (event) {

                                const item =
                                    document.createElement(
                                        'div'
                                    );


                                item.className =
                                    'owner-product-gallery-item';


                                const image =
                                    document.createElement(
                                        'img'
                                    );


                                image.src =
                                    event.target.result;


                                image.alt =
                                    'Ảnh xem trước';


                                item.appendChild(
                                    image
                                );


                                preview.appendChild(
                                    item
                                );
                            };


                        reader.readAsDataURL(
                            file
                        );

                    }
                );

            }
        );

    }
);

</script>


<?php

require BASE_PATH
    . '/app/views/layouts/footer.php';

?>
