<?php

require_once 'config.inc.php';
require_login();

/*
|--------------------------------------------------------------------------
| Product Image Configuration
|--------------------------------------------------------------------------
*/

define('PRODUCT_IMAGE_DIR', __DIR__ . '/uploads/products/');
define('PRODUCT_IMAGE_URL', 'uploads/products/');
define('MAX_PRODUCT_IMAGE_SIZE', 5 * 1024 * 1024); // 5MB


/*
|--------------------------------------------------------------------------
| Helper Functions
|--------------------------------------------------------------------------
*/

function uploadProductImage(string $fieldName): ?string
{
    if (
        !isset($_FILES[$fieldName]) ||
        $_FILES[$fieldName]['error'] === UPLOAD_ERR_NO_FILE
    ) {
        return null;
    }

    $file = $_FILES[$fieldName];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Image upload failed.');
    }

    if ($file['size'] > MAX_PRODUCT_IMAGE_SIZE) {
        throw new RuntimeException('Image size must be less than 5MB.');
    }

    /*
    |--------------------------------------------------------------------------
    | Validate actual MIME type
    |--------------------------------------------------------------------------
    */

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

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

    if (!isset($allowedTypes[$mime])) {
        throw new RuntimeException(
            'Invalid image format. Only JPG, PNG, WEBP and GIF are allowed.'
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Make sure it is actually an image
    |--------------------------------------------------------------------------
    */

    if (@getimagesize($file['tmp_name']) === false) {
        throw new RuntimeException(
            'Uploaded file is not a valid image.'
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Create upload directory if it does not exist
    |--------------------------------------------------------------------------
    */

    if (!is_dir(PRODUCT_IMAGE_DIR)) {
        if (!mkdir(PRODUCT_IMAGE_DIR, 0755, true)) {
            throw new RuntimeException(
                'Could not create product image directory.'
            );
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Generate safe random filename
    |--------------------------------------------------------------------------
    */

    $filename =
        'product_' .
        bin2hex(random_bytes(16)) .
        '.' .
        $allowedTypes[$mime];

    $destination = PRODUCT_IMAGE_DIR . $filename;

    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        throw new RuntimeException(
            'Could not save the uploaded product image.'
        );
    }

    return PRODUCT_IMAGE_URL . $filename;
}


function deleteProductImage(?string $imagePath): void
{
    if (!$imagePath) {
        return;
    }

    /*
    |--------------------------------------------------------------------------
    | Only delete files from uploads/products/
    |--------------------------------------------------------------------------
    */

    $filename = basename($imagePath);

    if (
        $filename === '' ||
        $filename === '.' ||
        $filename === '..'
    ) {
        return;
    }

    $file = PRODUCT_IMAGE_DIR . $filename;

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


/*
|--------------------------------------------------------------------------
| Request Handling
|--------------------------------------------------------------------------
*/

$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);


/*
|--------------------------------------------------------------------------
| POST
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    check_csrf();

    $op = $_POST['op'] ?? '';


    /*
    |--------------------------------------------------------------------------
    | SAVE PRODUCT
    |--------------------------------------------------------------------------
    */

    if ($op === 'save') {

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

        $brand = (int)($_POST['brand_id'] ?? 0);
        $model = trim($_POST['display_model'] ?? '');

        /*
        |--------------------------------------------------------------------------
        | Display Type
        |--------------------------------------------------------------------------
        | Only Incell and Oled are allowed.
        | Default = Incell
        |--------------------------------------------------------------------------
        */

        $type = $_POST['type'] ?? 'Incell';

        $allowedTypes = [
            'Incell',
            'Oled'
        ];

        if (!in_array($type, $allowedTypes, true)) {
            $type = 'Incell';
        }

        $qty = (int)($_POST['quantity'] ?? 0);
        $price = (float)($_POST['unit_price'] ?? 0);

        $compat = $_POST['compat'] ?? [];


        /*
        |--------------------------------------------------------------------------
        | Validate basic product data
        |--------------------------------------------------------------------------
        */

        if (
            !$brand ||
            $model === '' ||
            $qty < 0 ||
            $price < 0
        ) {

            flash(
                'danger',
                'Please enter valid display details.'
            );

            redirect(
                'products.php?action=' .
                ($id ? 'edit&id=' . $id : 'add')
            );
        }


        /*
        |--------------------------------------------------------------------------
        | Find existing image when editing
        |--------------------------------------------------------------------------
        */

        $oldImage = null;

        if ($id) {

            $existing = db()->prepare(
                "SELECT image_path
                 FROM products
                 WHERE id = ?"
            );

            $existing->bind_param(
                "i",
                $id
            );

            $existing->execute();

            $existingProduct =
                $existing
                    ->get_result()
                    ->fetch_assoc();

            if (!$existingProduct) {

                flash(
                    'danger',
                    'Display not found.'
                );

                redirect('products.php');
            }

            $oldImage =
                $existingProduct['image_path'] ?? null;
        }


        /*
        |--------------------------------------------------------------------------
        | Upload new image if supplied
        |--------------------------------------------------------------------------
        */

        $newImage = null;

        try {

            $newImage =
                uploadProductImage('product_image');

            $c = db();

            $c->begin_transaction();


            /*
            |--------------------------------------------------------------------------
            | INSERT / UPDATE PRODUCT
            |--------------------------------------------------------------------------
            */

            if ($id) {

                /*
                |--------------------------------------------------------------------------
                | UPDATE WITH NEW IMAGE
                |--------------------------------------------------------------------------
                */

                if ($newImage !== null) {

                    $s = $c->prepare(
                        "UPDATE products
                         SET brand_id = ?,
                             display_model = ?,
                             `type` = ?,
                             quantity = ?,
                             unit_price = ?,
                             image_path = ?
                         WHERE id = ?"
                    );

                    /*
                    | i = brand_id
                    | s = display_model
                    | s = type
                    | i = quantity
                    | d = unit_price
                    | s = image_path
                    | i = id
                    */

                    $s->bind_param(
                        "issidsi",
                        $brand,
                        $model,
                        $type,
                        $qty,
                        $price,
                        $newImage,
                        $id
                    );


                /*
                |--------------------------------------------------------------------------
                | UPDATE WITHOUT NEW IMAGE
                |--------------------------------------------------------------------------
                */

                } else {

                    $s = $c->prepare(
                        "UPDATE products
                         SET brand_id = ?,
                             display_model = ?,
                             `type` = ?,
                             quantity = ?,
                             unit_price = ?
                         WHERE id = ?"
                    );

                    /*
                    | i = brand_id
                    | s = display_model
                    | s = type
                    | i = quantity
                    | d = unit_price
                    | i = id
                    */

                    $s->bind_param(
                        "issidi",
                        $brand,
                        $model,
                        $type,
                        $qty,
                        $price,
                        $id
                    );
                }

                $s->execute();


            /*
            |--------------------------------------------------------------------------
            | INSERT NEW PRODUCT
            |--------------------------------------------------------------------------
            */

            } else {

                $s = $c->prepare(
                    "INSERT INTO products
                    (
                        brand_id,
                        display_model,
                        `type`,
                        quantity,
                        unit_price,
                        image_path
                    )
                    VALUES (?, ?, ?, ?, ?, ?)"
                );

                /*
                | i = brand_id
                | s = display_model
                | s = type
                | i = quantity
                | d = unit_price
                | s = image_path
                */

                $s->bind_param(
                    "issids",
                    $brand,
                    $model,
                    $type,
                    $qty,
                    $price,
                    $newImage
                );

                $s->execute();

                $id = $c->insert_id;
            }


            /*
            |--------------------------------------------------------------------------
            | Compatible Models
            |--------------------------------------------------------------------------
            */

            /*
            | First remove existing compatibility records.
            | This allows editing compatibility correctly.
            */

            $d = $c->prepare(
                "DELETE FROM compatible_models
                 WHERE product_id = ?"
            );

            $d->bind_param(
                "i",
                $id
            );

            $d->execute();


            /*
            |--------------------------------------------------------------------------
            | Insert Compatible Models
            |--------------------------------------------------------------------------
            */

            $ins = $c->prepare(
                "INSERT IGNORE INTO compatible_models
                (
                    product_id,
                    brand_id,
                    model_name
                )
                VALUES (?, ?, ?)"
            );


            if (is_array($compat)) {

                foreach ($compat as $x) {

                    $cb = (int)($x['brand_id'] ?? 0);

                    $cm = trim(
                        $x['model_name'] ?? ''
                    );

                    if ($cb && $cm !== '') {

                        $ins->bind_param(
                            "iis",
                            $id,
                            $cb,
                            $cm
                        );

                        $ins->execute();
                    }
                }
            }


            /*
            |--------------------------------------------------------------------------
            | Commit
            |--------------------------------------------------------------------------
            */

            $c->commit();


            /*
            |--------------------------------------------------------------------------
            | Delete old image only after DB update succeeds
            |--------------------------------------------------------------------------
            */

            if (
                $newImage !== null &&
                $oldImage !== null
            ) {

                deleteProductImage(
                    $oldImage
                );
            }


            flash(
                'success',
                'Display saved successfully.'
            );

            redirect('products.php');


        } catch (Throwable $e) {

            /*
            |--------------------------------------------------------------------------
            | Rollback database
            |--------------------------------------------------------------------------
            */

            if (isset($c)) {

                try {
                    $c->rollback();
                } catch (Throwable $ignored) {
                }
            }


            /*
            |--------------------------------------------------------------------------
            | Delete newly uploaded image if DB failed
            |--------------------------------------------------------------------------
            */

            if ($newImage !== null) {

                deleteProductImage(
                    $newImage
                );
            }


            flash(
                'danger',
                'Could not save display: ' .
                $e->getMessage()
            );

            redirect('products.php');
        }
    }


    /*
    |--------------------------------------------------------------------------
    | DELETE PRODUCT
    |--------------------------------------------------------------------------
    */

    if ($op === 'delete') {

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

        if (!$id) {

            flash(
                'danger',
                'Invalid display ID.'
            );

            redirect('products.php');
        }


        /*
        |--------------------------------------------------------------------------
        | Get image path before deleting product
        |--------------------------------------------------------------------------
        */

        $s = db()->prepare(
            "SELECT image_path
             FROM products
             WHERE id = ?"
        );

        $s->bind_param(
            "i",
            $id
        );

        $s->execute();

        $product =
            $s
                ->get_result()
                ->fetch_assoc();


        /*
        |--------------------------------------------------------------------------
        | Delete product
        |--------------------------------------------------------------------------
        */

        $s = db()->prepare(
            "DELETE FROM products
             WHERE id = ?"
        );

        $s->bind_param(
            "i",
            $id
        );

        $s->execute();


        /*
        |--------------------------------------------------------------------------
        | Delete image file
        |--------------------------------------------------------------------------
        */

        if ($product) {

            deleteProductImage(
                $product['image_path'] ?? null
            );
        }


        flash(
            'success',
            'Display deleted.'
        );

        redirect('products.php');
    }
}


/*
|--------------------------------------------------------------------------
| Brands
|--------------------------------------------------------------------------
*/

$brands = db()->query(
    "SELECT id, name
     FROM brands
     ORDER BY name"
);


/*
|--------------------------------------------------------------------------
| Edit Product
|--------------------------------------------------------------------------
*/

$edit = null;
$compatRows = [];

if ($action === 'edit' && $id) {

    $s = db()->prepare(
        "SELECT *
         FROM products
         WHERE id = ?"
    );

    $s->bind_param(
        "i",
        $id
    );

    $s->execute();

    $edit =
        $s
            ->get_result()
            ->fetch_assoc();


    if (!$edit) {

        flash(
            'danger',
            'Display not found.'
        );

        redirect('products.php');
    }


    /*
    |--------------------------------------------------------------------------
    | Compatible Models
    |--------------------------------------------------------------------------
    */

    $s = db()->prepare(
        "SELECT
            c.*,
            b.name AS brand
         FROM compatible_models c
         JOIN brands b
            ON b.id = c.brand_id
         WHERE c.product_id = ?
         ORDER BY c.id"
    );

    $s->bind_param(
        "i",
        $id
    );

    $s->execute();

    $rr = $s->get_result();

    while ($x = $rr->fetch_assoc()) {

        $compatRows[] = $x;
    }
}


/*
|--------------------------------------------------------------------------
| Page Title
|--------------------------------------------------------------------------
*/

$pageTitle =
    $action === 'list'
        ? 'Displays'
        : (
            $action === 'edit'
                ? 'Edit Display'
                : 'Add Display'
        );


include 'partials/header.php';


/*
|--------------------------------------------------------------------------
| ADD / EDIT
|--------------------------------------------------------------------------
*/

if (in_array($action, ['add', 'edit'])):
?>

<div class="card p-4">

    <div class="d-flex justify-content-between mb-4">

        <div>

            <h4>
                <?= $action === 'edit'
                    ? 'Edit Display'
                    : 'Add New Display'
                ?>
            </h4>

            <p class="text-secondary">
                Enter display information and compatible models.
            </p>

        </div>

        <a
            href="products.php"
            class="btn btn-light"
        >
            Back
        </a>

    </div>


    <div class="section-title mb-3">
        Display Information
    </div>


    <form
        method="post"
        enctype="multipart/form-data"
    >

        <input
            type="hidden"
            name="csrf"
            value="<?= e(csrf()) ?>"
        >

        <input
            type="hidden"
            name="op"
            value="save"
        >

        <input
            type="hidden"
            name="id"
            value="<?= e($edit['id'] ?? 0) ?>"
        >


        <div class="row g-3">


            <!-- Brand -->

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

                <label class="form-label">
                    Brand *
                </label>

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

                    <option value="">
                        Select Brand
                    </option>

                    <?php

                    $brands->data_seek(0);

                    while (
                        $b = $brands->fetch_assoc()
                    ):

                    ?>

                        <option
                            value="<?= $b['id'] ?>"
                            <?= (
                                $b['id'] ==
                                ($edit['brand_id'] ?? 0)
                            )
                                ? 'selected'
                                : ''
                            ?>
                        >

                            <?= e($b['name']) ?>

                        </option>

                    <?php endwhile; ?>

                </select>

            </div>


            <!-- Display Model -->

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

                <label class="form-label">
                    Display Model *
                </label>

                <input
                    class="form-control"
                    name="display_model"
                    value="<?= e(
                        $edit['display_model'] ?? ''
                    ) ?>"
                    placeholder="e.g. iPhone 11"
                    required
                >

            </div>


            <!-- Display Type -->

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

                <label class="form-label">
                    Type *
                </label>

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

                    <option
                        value="Incell"
                        <?= (
                            ($edit['type'] ?? 'Incell')
                            === 'Incell'
                        )
                            ? 'selected'
                            : ''
                        ?>
                    >
                        Incell
                    </option>

                    <option
                        value="Oled"
                        <?= (
                            ($edit['type'] ?? 'Incell')
                            === 'Oled'
                        )
                            ? 'selected'
                            : ''
                        ?>
                    >
                        Oled
                    </option>

                </select>

            </div>


            <!-- Quantity -->

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

                <label class="form-label">
                    Quantity *
                </label>

                <input
                    class="form-control"
                    type="number"
                    min="0"
                    name="quantity"
                    value="<?= e(
                        $edit['quantity'] ?? 0
                    ) ?>"
                    required
                >

            </div>


            <!-- Unit Price -->

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

                <label class="form-label">
                    Unit Price (Rs.) *
                </label>

                <input
                    class="form-control"
                    type="number"
                    min="0"
                    step="0.01"
                    name="unit_price"
                    value="<?= e(
                        $edit['unit_price'] ?? 0
                    ) ?>"
                    required
                >

            </div>


            <!-- Product Image -->

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

                <label class="form-label">
                    Product Image
                </label>

                <input
                    class="form-control"
                    type="file"
                    name="product_image"
                    accept="image/jpeg,image/png,image/webp,image/gif"
                >

                <div class="form-text">
                    JPG, PNG, WEBP or GIF. Maximum 5MB.
                </div>


                <?php

                if (
                    !empty($edit['image_path']) &&
                    is_file(
                        __DIR__ . '/' .
                        $edit['image_path']
                    )
                ):

                ?>

                    <div class="mt-3">

                        <div class="small text-secondary mb-2">
                            Current Image
                        </div>

                        <img
                            src="<?= e(
                                $edit['image_path']
                            ) ?>"
                            alt="<?= e(
                                $edit['display_model'] ?? 'Product'
                            ) ?>"
                            style="
                                width:140px;
                                height:140px;
                                object-fit:contain;
                                border:1px solid #dee2e6;
                                border-radius:8px;
                                padding:5px;
                                background:#fff;
                            "
                        >

                    </div>

                <?php endif; ?>

            </div>

        </div>


        <hr class="my-4">


        <!-- Compatible Models -->

        <div class="section-title mb-2">
            Compatible Models
        </div>


        <div class="alert alert-primary py-2">

            Select the compatible brand, then type the compatible
            phone model.

            <b>Different brands are supported.</b>

            Example: an OPPO display can be compatible with a
            Realme model.

        </div>


        <div id="compatBox">

            <?php if (!$compatRows): ?>

                <div class="row g-2 compat-row">

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

                        <select
                            name="compat[0][brand_id]"
                            class="form-select"
                        >

                            <?php

                            $brands->data_seek(0);

                            while (
                                $b =
                                $brands->fetch_assoc()
                            ):

                            ?>

                                <option
                                    value="<?= $b['id'] ?>"
                                >
                                    <?= e($b['name']) ?>
                                </option>

                            <?php endwhile; ?>

                        </select>

                    </div>


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

                        <input
                            class="form-control"
                            name="compat[0][model_name]"
                            placeholder="e.g. Realme 8"
                        >

                    </div>


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

                        <button
                            type="button"
                            class="btn btn-outline-danger remove w-100"
                        >
                            ×
                        </button>

                    </div>

                </div>

            <?php else: ?>


                <?php foreach (
                    $compatRows as $i => $x
                ): ?>

                    <div class="row g-2 compat-row">

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

                            <select
                                name="compat[<?= $i ?>][brand_id]"
                                class="form-select"
                            >

                                <?php

                                $brands->data_seek(0);

                                while (
                                    $b =
                                    $brands->fetch_assoc()
                                ):

                                ?>

                                    <option
                                        value="<?= $b['id'] ?>"
                                        <?= (
                                            $b['id'] ==
                                            $x['brand_id']
                                        )
                                            ? 'selected'
                                            : ''
                                        ?>
                                    >
                                        <?= e($b['name']) ?>
                                    </option>

                                <?php endwhile; ?>

                            </select>

                        </div>


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

                            <input
                                class="form-control"
                                name="compat[<?= $i ?>][model_name]"
                                value="<?= e(
                                    $x['model_name']
                                ) ?>"
                                placeholder="e.g. Realme 8"
                            >

                        </div>


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

                            <button
                                type="button"
                                class="btn btn-outline-danger remove w-100"
                            >
                                ×
                            </button>

                        </div>

                    </div>

                <?php endforeach; ?>

            <?php endif; ?>

        </div>


        <button
            type="button"
            id="addCompat"
            class="btn btn-outline-primary mt-2"
        >
            + Add Another Compatible Model
        </button>


        <div>

            <button
                type="submit"
                class="btn btn-primary mt-4 px-4"
            >
                ✓ Save Display
            </button>

        </div>

    </form>

</div>


<script>

let n =
    document.querySelectorAll('.compat-row').length;


const brandOptions = `
<?php

$brands->data_seek(0);

while (
    $b = $brands->fetch_assoc()
):

?>

<option value="<?= $b['id'] ?>">
    <?= e($b['name']) ?>
</option>

<?php endwhile; ?>

`;


const addCompatButton =
    document.getElementById('addCompat');


if (addCompatButton) {

    addCompatButton.onclick = () => {

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

        row.className =
            'row g-2 compat-row';


        row.innerHTML = `

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

                <select
                    name="compat[${n}][brand_id]"
                    class="form-select"
                >

                    ${brandOptions}

                </select>

            </div>


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

                <input
                    class="form-control"
                    name="compat[${n}][model_name]"
                    placeholder="e.g. Realme 8"
                >

            </div>


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

                <button
                    type="button"
                    class="btn btn-outline-danger remove w-100"
                >
                    ×
                </button>

            </div>

        `;


        document
            .getElementById('compatBox')
            .appendChild(row);

        n++;

    };

}


document.addEventListener(
    'click',
    e => {

        const button =
            e.target.closest('.remove');

        if (!button) {
            return;
        }


        const row =
            button.closest('.compat-row');

        if (row) {
            row.remove();
        }

    }
);

</script>


<?php else: ?>


<!--
|--------------------------------------------------------------------------
| PRODUCT LIST
|--------------------------------------------------------------------------
-->

<div class="card p-4">

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

        <div>

            <h5>
                Display Inventory
            </h5>

            <p class="text-secondary">
                Displays, stock, unit prices,
                images and cross-brand compatibility.
            </p>

        </div>


        <a
            href="products.php?action=add"
            class="btn btn-primary"
        >
            + Add Display
        </a>

    </div>


    <div class="table-responsive">

        <table class="table align-middle">

            <thead>

                <tr>

                    <th style="width:80px;">
                        Image
                    </th>

                    <th>
                        Brand
                    </th>

                    <th>
                        Display
                    </th>

                    <th>
                        Type
                    </th>

                    <th>
                        Qty
                    </th>

                    <th>
                        Unit Price
                    </th>

                    <th>
                        Compatible
                    </th>

                    <th>
                    </th>

                </tr>

            </thead>


            <tbody>

                <?php

                $rows = db()->query(
                    "SELECT
                        p.*,
                        b.name AS brand,

                        (
                            SELECT COUNT(*)
                            FROM compatible_models c
                            WHERE c.product_id = p.id
                        ) AS cc

                     FROM products p

                     JOIN brands b
                        ON b.id = p.brand_id

                     ORDER BY p.id DESC"
                );


                while (
                    $r = $rows->fetch_assoc()
                ):

                ?>

                    <tr>


                        <!-- Product Image -->

                        <td>

                            <?php

                            $hasImage =
                                !empty($r['image_path']) &&
                                is_file(
                                    __DIR__ . '/' .
                                    $r['image_path']
                                );

                            ?>

                            <?php if ($hasImage): ?>

                                <img
                                    src="<?= e(
                                        $r['image_path']
                                    ) ?>"
                                    alt="<?= e(
                                        $r['display_model']
                                    ) ?>"
                                    class="product-thumb"
                                    data-bs-toggle="modal"
                                    data-bs-target="#imageModal"
                                    data-image="<?= e(
                                        $r['image_path']
                                    ) ?>"
                                    data-title="<?= e(
                                        $r['display_model']
                                    ) ?>"
                                    style="
                                        width:60px;
                                        height:60px;
                                        object-fit:contain;
                                        border:1px solid #dee2e6;
                                        border-radius:6px;
                                        padding:3px;
                                        background:#fff;
                                        cursor:zoom-in;
                                    "
                                >

                            <?php else: ?>

                                <div
                                    style="
                                        width:60px;
                                        height:60px;
                                        display:flex;
                                        align-items:center;
                                        justify-content:center;
                                        background:#f8f9fa;
                                        border:1px solid #dee2e6;
                                        border-radius:6px;
                                        color:#adb5bd;
                                        font-size:12px;
                                    "
                                >
                                    No Image
                                </div>

                            <?php endif; ?>

                        </td>


                        <!-- Brand -->

                        <td>

                            <?= e(
                                $r['brand']
                            ) ?>

                        </td>


                        <!-- Display -->

                        <td class="fw-semibold">

                            <?= e(
                                $r['display_model']
                            ) ?>

                        </td>


                        <!-- Type -->

                        <td>

                            <?php if (
                                ($r['type'] ?? 'Incell')
                                === 'Oled'
                            ): ?>

                                <span class="badge bg-dark">
                                    Oled
                                </span>

                            <?php else: ?>

                                <span class="badge bg-primary">
                                    Incell
                                </span>

                            <?php endif; ?>

                        </td>


                        <!-- Quantity -->

                        <td>

                            <?= (int)$r['quantity'] ?>

                        </td>


                        <!-- Price -->

                        <td>

                            Rs.
                            <?= number_format(
                                (float)$r['unit_price'],
                                2
                            ) ?>

                        </td>


                        <!-- Compatible Models -->

                        <td>

                            <?= (int)$r['cc'] ?>
                            models

                        </td>


                        <!-- Actions -->

                        <td>

                            <a
                                class="btn btn-sm btn-outline-secondary"
                                href="?action=edit&id=<?= $r['id'] ?>"
                            >
                                Edit
                            </a>


                            <form
                                class="d-inline"
                                method="post"
                            >

                                <input
                                    type="hidden"
                                    name="csrf"
                                    value="<?= e(csrf()) ?>"
                                >

                                <input
                                    type="hidden"
                                    name="op"
                                    value="delete"
                                >

                                <input
                                    type="hidden"
                                    name="id"
                                    value="<?= $r['id'] ?>"
                                >


                                <button
                                    type="submit"
                                    class="btn btn-sm btn-outline-danger"
                                    data-confirm="Delete this display?"
                                >
                                    Delete
                                </button>

                            </form>

                        </td>

                    </tr>

                <?php endwhile; ?>

            </tbody>

        </table>

    </div>

</div>


<?php endif; ?>


<!--
|--------------------------------------------------------------------------
| Product Image Zoom Modal
|--------------------------------------------------------------------------
-->

<div
    class="modal fade"
    id="imageModal"
    tabindex="-1"
    aria-hidden="true"
>

    <div class="modal-dialog modal-dialog-centered modal-xl">

        <div class="modal-content">

            <div class="modal-header">

                <h5
                    class="modal-title"
                    id="imageModalTitle"
                >
                    Product Image
                </h5>

                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>

            </div>


            <div class="modal-body text-center">

                <img
                    id="zoomedProductImage"
                    src=""
                    alt=""
                    style="
                        max-width:100%;
                        max-height:75vh;
                        object-fit:contain;
                        cursor:zoom-in;
                        transition:transform 0.2s ease;
                    "
                >

            </div>

        </div>

    </div>

</div>


<script>

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

        const imageModal =
            document.getElementById('imageModal');

        const zoomedImage =
            document.getElementById(
                'zoomedProductImage'
            );

        const imageTitle =
            document.getElementById(
                'imageModalTitle'
            );


        if (!imageModal || !zoomedImage) {
            return;
        }


        imageModal.addEventListener(
            'show.bs.modal',
            function (event) {

                const thumbnail =
                    event.relatedTarget;

                if (!thumbnail) {
                    return;
                }


                const image =
                    thumbnail.getAttribute(
                        'data-image'
                    );

                const title =
                    thumbnail.getAttribute(
                        'data-title'
                    );


                zoomedImage.src =
                    image || '';

                zoomedImage.alt =
                    title || '';

                if (imageTitle) {

                    imageTitle.textContent =
                        title || 'Product Image';

                }


                /*
                |--------------------------------------------------------------------------
                | Reset zoom
                |--------------------------------------------------------------------------
                */

                zoomedImage.style.transform =
                    'scale(1)';

                zoomedImage.style.cursor =
                    'zoom-in';

            }
        );


        /*
        |--------------------------------------------------------------------------
        | Click large image to zoom
        |--------------------------------------------------------------------------
        */

        zoomedImage.addEventListener(
            'click',
            function () {

                if (
                    zoomedImage.style.transform ===
                    'scale(1.5)'
                ) {

                    zoomedImage.style.transform =
                        'scale(1)';

                    zoomedImage.style.cursor =
                        'zoom-in';

                } else {

                    zoomedImage.style.transform =
                        'scale(1.5)';

                    zoomedImage.style.cursor =
                        'zoom-out';
                }

            }
        );


        /*
        |--------------------------------------------------------------------------
        | Reset when modal closes
        |--------------------------------------------------------------------------
        */

        imageModal.addEventListener(
            'hidden.bs.modal',
            function () {

                zoomedImage.src = '';

                zoomedImage.style.transform =
                    'scale(1)';

                zoomedImage.style.cursor =
                    'zoom-in';

            }
        );

    }
);

</script>


<?php

include 'partials/footer.php';

?>