<?php

require_once __DIR__ . "/config.inc.php";

/*
|--------------------------------------------------------------------------
| LOGIN REQUIRED
|--------------------------------------------------------------------------
|
| If the user is not logged in, require_login() should redirect them
| to your login page.
|
*/


/*
|--------------------------------------------------------------------------
| SESSION
|--------------------------------------------------------------------------
*/

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['order_cart'])) {
    $_SESSION['order_cart'] = [];
}


/*
|--------------------------------------------------------------------------
| DISPLAY TYPES
|--------------------------------------------------------------------------
|
| Only these two types are allowed.
| Incell is the default.
|
*/

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


/*
|--------------------------------------------------------------------------
| Helper: Set message
|--------------------------------------------------------------------------
*/

function orderMessage(string $type, string $message): void
{
    $_SESSION['order_message'] = [
        'type'    => $type,
        'message' => $message
    ];
}


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

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

    /*
    |--------------------------------------------------------------------------
    | CSRF
    |--------------------------------------------------------------------------
    */

    $token = $_POST['csrf_token'] ?? '';

    if (function_exists('user_csrf')) {

        if (!hash_equals(user_csrf(), $token)) {

            orderMessage(
                'danger',
                'Invalid security token. Please try again.'
            );

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }
    }


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


    /*
    |--------------------------------------------------------------------------
    | ADD TO ORDER QUEUE
    |--------------------------------------------------------------------------
    */

    if ($action === 'add_to_cart') {

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

        $qty = (int)($_POST['qty'] ?? 1);

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

        $phoneModel = trim(
            $_POST['phone_model'] ?? ''
        );


        /*
        |--------------------------------------------------------------------------
        | Display Type
        |--------------------------------------------------------------------------
        */

        $displayType = trim(
            $_POST['display_type'] ?? 'Incell'
        );


        /*
        | Only Incell and Oled are allowed
        */

        if (!in_array($displayType, $displayTypes, true)) {
            $displayType = 'Incell';
        }


        /*
        |--------------------------------------------------------------------------
        | Basic Validation
        |--------------------------------------------------------------------------
        */

        if ($productId <= 0) {

            orderMessage(
                'danger',
                'Invalid display selected.'
            );

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }


        if ($qty <= 0) {

            orderMessage(
                'danger',
                'Please enter a valid quantity.'
            );

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }


        /*
        |--------------------------------------------------------------------------
        | Get Product
        |--------------------------------------------------------------------------
        */

        $stmt = db()->prepare("
            SELECT
                p.id,
                p.display_model,
                p.unit_price,
                p.quantity,
                p.type,
                p.image_path,
                b.name AS brand_name

            FROM products p

            JOIN brands b
                ON b.id = p.brand_id

            WHERE p.id = ?
            LIMIT 1
        ");

        $stmt->bind_param(
            "i",
            $productId
        );

        $stmt->execute();

        $prod = $stmt
            ->get_result()
            ->fetch_assoc();

        $stmt->close();


        /*
        |--------------------------------------------------------------------------
        | Product Not Found
        |--------------------------------------------------------------------------
        */

        if (!$prod) {

            orderMessage(
                'danger',
                'The selected display could not be found.'
            );

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }


        /*
        |--------------------------------------------------------------------------
        | Current Database Stock
        |--------------------------------------------------------------------------
        */

        $availableQty = (int)$prod['quantity'];


        /*
        |--------------------------------------------------------------------------
        | Product Out Of Stock
        |--------------------------------------------------------------------------
        */

        if ($availableQty <= 0) {

            orderMessage(
                'warning',
                'Sorry, ' .
                $prod['display_model'] .
                ' is currently out of stock.'
            );

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }


        /*
        |--------------------------------------------------------------------------
        | Cart Key
        |--------------------------------------------------------------------------
        |
        | Same display + same type = same cart item.
        |
        */

        $cartKey =
            $productId .
            '_' .
            strtolower($displayType);


        /*
        |--------------------------------------------------------------------------
        | Existing Quantity In Cart
        |--------------------------------------------------------------------------
        */

        $existingQty = 0;

        if (isset($_SESSION['order_cart'][$cartKey])) {

            $existingQty = (int)(
                $_SESSION['order_cart'][$cartKey]['qty']
                ?? 0
            );
        }


        /*
        |--------------------------------------------------------------------------
        | Validate Total Requested Quantity
        |--------------------------------------------------------------------------
        |
        | Example:
        |
        | Stock = 5
        | Already in cart = 3
        | User requests = 3
        |
        | Total = 6
        |
        | Therefore reject.
        |
        */

        $totalRequested =
            $existingQty + $qty;


        if ($totalRequested > $availableQty) {

            $remaining =
                max(
                    0,
                    $availableQty - $existingQty
                );

            if ($remaining > 0) {

                $message =
                    'Not enough stock available for ' .
                    $prod['display_model'] .
                    '. You can add only ' .
                    $remaining .
                    ' more item(s) to your order.';

            } else {

                $message =
                    'You have already added the available stock of ' .
                    $prod['display_model'] .
                    ' to your order.';
            }


            orderMessage(
                'warning',
                $message
            );

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }


        /*
        |--------------------------------------------------------------------------
        | Save / Update Cart
        |--------------------------------------------------------------------------
        */

        if (isset($_SESSION['order_cart'][$cartKey])) {

            $_SESSION['order_cart'][$cartKey]['qty']
                += $qty;

        } else {

            $_SESSION['order_cart'][$cartKey] = [

                'product_id' =>
                    $productId,

                'display_brand_name' =>
                    $prod['brand_name'],

                'display_model' =>
                    $prod['display_model'],

                'unit_price' =>
                    (float)$prod['unit_price'],

                'display_type' =>
                    $displayType,

                'qty' =>
                    $qty,

                'phone_brand_id' =>
                    $phoneBrandId,

                'phone_model' =>
                    $phoneModel,

                'image_path' =>
                    $prod['image_path'] ?? null
            ];
        }


        /*
        |--------------------------------------------------------------------------
        | Success Message
        |--------------------------------------------------------------------------
        */

        orderMessage(
            'success',
            $qty .
            ' item(s) added to your order queue.'
        );


        /*
        |--------------------------------------------------------------------------
        | Redirect
        |--------------------------------------------------------------------------
        */

        header(
            "Location: " .
            $_SERVER['REQUEST_URI']
        );

        exit;
    }


    /*
    |--------------------------------------------------------------------------
    | REMOVE ITEM
    |--------------------------------------------------------------------------
    */

    if ($action === 'remove_from_cart') {

        $cartKey =
            $_POST['cart_key'] ?? '';

        if (
            $cartKey !== '' &&
            isset($_SESSION['order_cart'][$cartKey])
        ) {

            unset(
                $_SESSION['order_cart'][$cartKey]
            );

            orderMessage(
                'success',
                'Item removed from the order queue.'
            );

        } else {

            orderMessage(
                'warning',
                'Order item was not found.'
            );
        }


        header(
            "Location: " .
            $_SERVER['REQUEST_URI']
        );

        exit;
    }


    /*
    |--------------------------------------------------------------------------
    | CLEAR CART
    |--------------------------------------------------------------------------
    */

    if ($action === 'clear_cart') {

        $_SESSION['order_cart'] = [];

        orderMessage(
            'success',
            'Order queue cleared.'
        );


        header(
            "Location: " .
            $_SERVER['REQUEST_URI']
        );

        exit;
    }
}


/*
|--------------------------------------------------------------------------
| Get Flash Message
|--------------------------------------------------------------------------
*/

$orderMessage = null;

if (isset($_SESSION['order_message'])) {

    $orderMessage =
        $_SESSION['order_message'];

    unset(
        $_SESSION['order_message']
    );
}


/*
|--------------------------------------------------------------------------
| FETCH BRANDS
|--------------------------------------------------------------------------
*/

$brands = [];

$res = db()->query("
    SELECT
        id,
        name

    FROM brands

    ORDER BY name
");

while ($r = $res->fetch_assoc()) {

    $brands[] = $r;
}


/*
|--------------------------------------------------------------------------
| SEARCH PARAMETERS
|--------------------------------------------------------------------------
*/

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

$model = trim(
    $_GET['model'] ?? ''
);


/*
|--------------------------------------------------------------------------
| SEARCH RESULTS
|--------------------------------------------------------------------------
*/

$results = [];


if (
    $brand_id > 0 &&
    $model !== ''
) {

    /*
    |--------------------------------------------------------------------------
    | Find:
    |
    | 1. Product belonging to selected brand/model
    |
    | OR
    |
    | 2. Product compatible with selected brand/model
    |--------------------------------------------------------------------------
    */

    $sql = "
        SELECT DISTINCT

            p.id AS product_id,

            p.brand_id AS display_brand_id,

            b.name AS display_brand_name,

            p.display_model,

            p.quantity,

            p.unit_price,

            p.type,

            p.image_path

        FROM products p

        JOIN brands b
            ON b.id = p.brand_id

        WHERE

            (
                p.brand_id = ?
                AND p.display_model = ?
            )

            OR

            p.id IN (

                SELECT
                    cm.product_id

                FROM compatible_models cm

                WHERE
                    cm.brand_id = ?
                    AND cm.model_name = ?
            )

        ORDER BY
            b.name,
            p.display_model
    ";


    $stmt = db()->prepare(
        $sql
    );


    $stmt->bind_param(
        "isis",
        $brand_id,
        $model,
        $brand_id,
        $model
    );


    $stmt->execute();

    $res =
        $stmt->get_result();


    while (
        $row =
            $res->fetch_assoc()
    ) {

        $results[] = $row;
    }


    $stmt->close();
}


/*
|--------------------------------------------------------------------------
| HEADER
|--------------------------------------------------------------------------
*/

require_once __DIR__ .
    "/partials/header.php";

?>

<div class="row g-4">


    <!--
    |--------------------------------------------------------------------------
    | LEFT COLUMN
    |--------------------------------------------------------------------------
    -->

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


        <!--
        |--------------------------------------------------------------------------
        | FLASH MESSAGE
        |--------------------------------------------------------------------------
        -->

        <?php if ($orderMessage): ?>

            <?php

            $alertClass =
                $orderMessage['type'] === 'success'
                    ? 'alert-success'
                    : (
                        $orderMessage['type'] === 'warning'
                            ? 'alert-warning'
                            : 'alert-danger'
                    );

            ?>

            <div
                class="alert <?= $alertClass ?> alert-dismissible fade show"
                role="alert"
            >

                <?= e(
                    $orderMessage['message']
                ) ?>

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

            </div>

        <?php endif; ?>


        <!--
        |--------------------------------------------------------------------------
        | SEARCH FORM
        |--------------------------------------------------------------------------
        -->

        <div class="card shadow-sm mb-4">

            <div class="card-body">

                <h5 class="card-title mb-3">
                    Find Display by Phone Model
                </h5>


                <form
                    method="get"
                    class="row g-3"
                >


                    <!-- Phone Brand -->

                    <div class="col-12">

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


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

                            <option value="">
                                Select brand...
                            </option>


                            <?php foreach (
                                $brands as $b
                            ): ?>

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

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

                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!--
                    |--------------------------------------------------------------------------
                    | Phone Model - AUTOCOMPLETE
                    |--------------------------------------------------------------------------
                    -->

                    <div class="col-12">

                        <label class="form-label">
                            Phone Model
                        </label>


                        <div class="position-relative">

                            <input
                                type="text"
                                class="form-control"
                                name="model"
                                id="modelInput"
                                value="<?= e($model) ?>"
                                placeholder="Type phone model..."
                                autocomplete="off"
                                required
                                disabled
                            >


                            <div
                                id="modelSuggestions"
                                class="list-group position-absolute w-100 shadow-sm"
                                style="
                                    z-index:1050;
                                    display:none;
                                    max-height:240px;
                                    overflow-y:auto;
                                "
                            ></div>

                        </div>


                        <div class="form-text">
                            Start typing to find phone models for the selected brand.
                        </div>

                    </div>


                    <!-- Search -->

                    <div class="col-12 d-grid">

                        <button
                            type="submit"
                            class="btn btn-dark"
                        >
                            Search Displays
                        </button>

                    </div>

                </form>

            </div>

        </div>


        <!--
        |--------------------------------------------------------------------------
        | ORDER QUEUE
        |--------------------------------------------------------------------------
        -->

        <div
            class="card shadow-sm border-primary mb-4"
        >

            <div
                class="card-header bg-primary text-white d-flex justify-content-between align-items-center py-2"
            >

                <h6 class="mb-0 fw-bold">

                    🛒 Current Order Queue
                    (<?= count(
                        $_SESSION['order_cart']
                    ) ?>)

                </h6>


                <?php if (
                    !empty($_SESSION['order_cart'])
                ): ?>

                    <form
                        method="post"
                        class="d-inline"
                        onsubmit="
                            return confirm(
                                'Clear all items from order queue?'
                            );
                        "
                    >

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

                        <input
                            type="hidden"
                            name="action"
                            value="clear_cart"
                        >


                        <button
                            type="submit"
                            class="btn btn-sm btn-outline-light py-0 px-2"
                            style="font-size:0.75rem;"
                        >
                            Clear All
                        </button>

                    </form>

                <?php endif; ?>

            </div>


            <div class="card-body p-0">


                <?php if (
                    empty($_SESSION['order_cart'])
                ): ?>

                    <div
                        class="p-3 text-muted text-center small"
                    >

                        No displays added yet.

                        Search a phone model and
                        add displays to your order queue.

                    </div>


                <?php else: ?>


                    <div class="table-responsive">

                        <table
                            class="table table-sm align-middle mb-0 small"
                        >

                            <thead class="table-light">

                                <tr>

                                    <th>
                                        Item / Type
                                    </th>

                                    <th class="text-center">
                                        Qty
                                    </th>

                                    <th class="text-end">
                                        Price
                                    </th>

                                    <th>
                                    </th>

                                </tr>

                            </thead>


                            <tbody>

                                <?php

                                $grandTotal = 0;

                                foreach (
                                    $_SESSION['order_cart']
                                    as $key => $item
                                ):

                                    $itemQty =
                                        (int)$item['qty'];

                                    $itemPrice =
                                        (float)$item['unit_price'];

                                    $itemSubtotal =
                                        $itemPrice *
                                        $itemQty;

                                    $grandTotal +=
                                        $itemSubtotal;

                                ?>

                                    <tr>

                                        <td>

                                            <div
                                                class="fw-bold"
                                            >

                                                <?= e(
                                                    $item[
                                                        'display_brand_name'
                                                    ]
                                                ) ?>

                                                /

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

                                            </div>


                                            <div
                                                class="text-muted"
                                                style="
                                                    font-size:0.75rem;
                                                "
                                            >

                                                Type:

                                                <?= e(
                                                    $item[
                                                        'display_type'
                                                    ]
                                                ) ?>

                                            </div>

                                        </td>


                                        <td
                                            class="text-center fw-semibold"
                                        >

                                            <?= $itemQty ?>

                                        </td>


                                        <td class="text-end">

                                            Rs.

                                            <?= number_format(
                                                $itemSubtotal,
                                                2
                                            ) ?>

                                        </td>


                                        <td
                                            class="text-center"
                                        >

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

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

                                                <input
                                                    type="hidden"
                                                    name="action"
                                                    value="remove_from_cart"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="cart_key"
                                                    value="<?= e(
                                                        $key
                                                    ) ?>"
                                                >


                                                <button
                                                    type="submit"
                                                    class="btn btn-link text-danger p-0 border-0 text-decoration-none"
                                                    title="Remove"
                                                >
                                                    &times;
                                                </button>

                                            </form>

                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            </tbody>


                            <tfoot
                                class="table-group-divider"
                            >

                                <tr
                                    class="fw-bold"
                                >

                                    <td
                                        colspan="2"
                                        class="ps-2"
                                    >
                                        Total Amount:
                                    </td>


                                    <td
                                        class="text-end text-success"
                                    >

                                        Rs.

                                        <?= number_format(
                                            $grandTotal,
                                            2
                                        ) ?>

                                    </td>


                                    <td>
                                    </td>

                                </tr>

                            </tfoot>

                        </table>

                    </div>


                    <!-- Submit Order -->

                    <div
                        class="p-3 bg-light border-top"
                    >

                        <form
                            method="post"
                            action="place_order.php"
                        >

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


                            <button
                                type="submit"
                                class="btn btn-success w-100 fw-bold"
                            >
                                Submit Order Now
                            </button>

                        </form>

                    </div>

                <?php endif; ?>

            </div>

        </div>

    </div>


    <!--
    |--------------------------------------------------------------------------
    | RIGHT COLUMN
    |--------------------------------------------------------------------------
    -->

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

        <div class="card shadow-sm">

            <div class="card-body">

                <h5 class="mb-3">
                    Available Displays
                </h5>


                <?php if (
                    $brand_id > 0 &&
                    $model !== '' &&
                    !$results
                ): ?>

                    <div
                        class="alert alert-warning mb-0"
                    >

                        No display found for this model.

                    </div>

                <?php endif; ?>


                <?php foreach (
                    $results as $p
                ): ?>


                    <?php

                    /*
                    |--------------------------------------------------------------------------
                    | Image
                    |--------------------------------------------------------------------------
                    */

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


                    /*
                    |--------------------------------------------------------------------------
                    | Availability
                    |--------------------------------------------------------------------------
                    */

                    $isAvailable =
                        (int)$p['quantity'] > 0;


                    /*
                    |--------------------------------------------------------------------------
                    | Product Type
                    |--------------------------------------------------------------------------
                    */

                    $productType =
                        trim(
                            $p['type'] ?? ''
                        );


                    if (
                        !in_array(
                            $productType,
                            $displayTypes,
                            true
                        )
                    ) {

                        $productType =
                            'Incell';
                    }

                    ?>


                    <div
                        class="border rounded p-3 mb-3"
                    >

                        <div
                            class="row g-3 align-items-center"
                        >


                            <!-- Product Image -->

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

                                <?php if ($hasImage): ?>

                                    <img
                                        src="<?= e(
                                            "../admin/" .
                                            $p['image_path']
                                        ) ?>"
                                        alt="<?= e(
                                            $p['display_model']
                                        ) ?>"
                                        class="search-product-image"
                                        data-bs-toggle="modal"
                                        data-bs-target="#productImageModal"
                                        data-image="<?= e(
                                            "../admin/" .
                                            $p['image_path']
                                        ) ?>"
                                        data-title="<?= e(
                                            $p['display_brand_name'] .
                                            ' / ' .
                                            $p['display_model']
                                        ) ?>"
                                        style="
                                            width:120px;
                                            height:120px;
                                            max-width:100%;
                                            object-fit:contain;
                                            border:1px solid #dee2e6;
                                            border-radius:8px;
                                            padding:5px;
                                            background:#fff;
                                            cursor:zoom-in;
                                        "
                                    >

                                <?php else: ?>

                                    <div
                                        style="
                                            width:120px;
                                            height:120px;
                                            max-width:100%;
                                            margin:auto;
                                            display:flex;
                                            align-items:center;
                                            justify-content:center;
                                            background:#f8f9fa;
                                            border:1px solid #dee2e6;
                                            border-radius:8px;
                                            color:#adb5bd;
                                        "
                                    >
                                        No Image
                                    </div>

                                <?php endif; ?>

                            </div>


                            <!-- Product Details -->

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


                                <div
                                    class="fw-bold fs-5"
                                >

                                    <?= e(
                                        $p[
                                            'display_brand_name'
                                        ]
                                    ) ?>

                                    /

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

                                </div>


                                <div
                                    class="mt-1 text-muted"
                                >

                                    <span
                                        class="fw-semibold text-dark"
                                    >
                                        Price:
                                    </span>

                                    Rs.

                                    <?= number_format(
                                        (float)$p[
                                            'unit_price'
                                        ],
                                        2
                                    ) ?>

                                </div>


                                <?php if ($isAvailable): ?>


                                    <form
                                        method="post"
                                        class="row g-2 align-items-end mt-2"
                                    >

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


                                        <input
                                            type="hidden"
                                            name="action"
                                            value="add_to_cart"
                                        >


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


                                        <input
                                            type="hidden"
                                            name="phone_brand_id"
                                            value="<?= (int)$brand_id ?>"
                                        >


                                        <input
                                            type="hidden"
                                            name="phone_model"
                                            value="<?= e(
                                                $model
                                            ) ?>"
                                        >


                                        <!-- Display Type -->

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

                                            <label
                                                class="form-label small mb-1"
                                            >
                                                Display Type
                                            </label>


                                            <select
                                                class="form-select form-select-sm"
                                                name="display_type"
                                                required
                                            >

                                                <?php foreach (
                                                    $displayTypes
                                                    as $type
                                                ): ?>

                                                    <option
                                                        value="<?= e(
                                                            $type
                                                        ) ?>"
                                                        <?= (
                                                            $type ===
                                                            'Incell'
                                                        )
                                                            ? 'selected'
                                                            : ''
                                                        ?>
                                                    >

                                                        <?= e(
                                                            $type
                                                        ) ?>

                                                    </option>

                                                <?php endforeach; ?>

                                            </select>

                                        </div>


                                        <!-- Quantity -->

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

                                            <label
                                                class="form-label small mb-1"
                                            >
                                                Quantity
                                            </label>


                                            <input
                                                class="form-control form-control-sm"
                                                type="number"
                                                name="qty"
                                                min="1"
                                                value="1"
                                                required
                                            >

                                        </div>


                                        <!-- Add -->

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

                                            <button
                                                type="submit"
                                                class="btn btn-outline-primary btn-sm fw-semibold"
                                            >

                                                + Add to Order Queue

                                            </button>

                                        </div>

                                    </form>


                                <?php else: ?>


                                    <div
                                        class="alert alert-secondary py-2 px-2 mt-2 mb-0 small"
                                    >

                                        Currently unavailable.

                                    </div>

                                <?php endif; ?>


                            </div>

                        </div>

                    </div>


                <?php endforeach; ?>


                <?php if (
                    !$results &&
                    !(
                        $brand_id > 0 &&
                        $model !== ''
                    )
                ): ?>

                    <div class="text-muted">

                        Search by brand and model
                        to see available displays.

                    </div>

                <?php endif; ?>


            </div>

        </div>

    </div>

</div>


<!--
|--------------------------------------------------------------------------
| PRODUCT IMAGE MODAL
|--------------------------------------------------------------------------
-->

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

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

        <div class="modal-content">


            <div class="modal-header">

                <h5
                    class="modal-title"
                    id="productImageModalTitle"
                >
                    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>

/*
|--------------------------------------------------------------------------
| Brand / Model Auto Suggest
|--------------------------------------------------------------------------
*/

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

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

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


/*
|--------------------------------------------------------------------------
| Store Models
|--------------------------------------------------------------------------
*/

let availableModels = [];


/*
|--------------------------------------------------------------------------
| Load Models
|--------------------------------------------------------------------------
*/

async function loadModels(
    brandId,
    selectedModel = ""
) {

    availableModels = [];

    modelInput.value =
        selectedModel || "";

    modelInput.disabled = true;

    modelInput.placeholder =
        "Loading models...";

    modelSuggestions.innerHTML = "";

    modelSuggestions.style.display =
        "none";


    if (!brandId) {

        modelInput.disabled = true;

        modelInput.placeholder =
            "Select brand first...";

        return;
    }


    try {

        const res =
            await fetch(
                'ajax_models.php?brand_id=' +
                encodeURIComponent(brandId)
            );


        if (!res.ok) {

            throw new Error(
                'Could not load models.'
            );
        }


        const models =
            await res.json();


        availableModels =
            Array.isArray(models)
                ? models
                : [];


        modelInput.disabled = false;

        modelInput.placeholder =
            "Type phone model...";


        if (selectedModel) {

            modelInput.value =
                selectedModel;
        }


    } catch (error) {

        console.error(error);

        modelInput.disabled = false;

        modelInput.placeholder =
            "Unable to load models";

        availableModels = [];
    }
}


/*
|--------------------------------------------------------------------------
| Show Suggestions
|--------------------------------------------------------------------------
*/

function showModelSuggestions()
{
    const searchText =
        modelInput.value
            .trim()
            .toLowerCase();


    modelSuggestions.innerHTML = "";


    if (
        !searchText ||
        !availableModels.length
    ) {

        modelSuggestions.style.display =
            "none";

        return;
    }


    /*
    |--------------------------------------------------------------------------
    | Filter Models
    |--------------------------------------------------------------------------
    |
    | Models starting with the typed text are shown first.
    | Then models containing the typed text anywhere.
    |
    */

    const matches =
        availableModels
            .filter(function(model) {

                return String(model)
                    .toLowerCase()
                    .includes(searchText);

            })
            .sort(function(a, b) {

                const aText =
                    String(a).toLowerCase();

                const bText =
                    String(b).toLowerCase();

                const aStarts =
                    aText.startsWith(searchText);

                const bStarts =
                    bText.startsWith(searchText);


                if (
                    aStarts &&
                    !bStarts
                ) {
                    return -1;
                }


                if (
                    !aStarts &&
                    bStarts
                ) {
                    return 1;
                }


                return aText.localeCompare(
                    bText
                );

            })
            .slice(0, 30);


    if (!matches.length) {

        modelSuggestions.style.display =
            "none";

        return;
    }


    /*
    |--------------------------------------------------------------------------
    | Create Suggestion Items
    |--------------------------------------------------------------------------
    */

    matches.forEach(function(model) {

        const item =
            document.createElement("button");


        item.type =
            "button";


        item.className =
            "list-group-item list-group-item-action";


        item.textContent =
            model;


        /*
        |--------------------------------------------------------------------------
        | Select Model
        |--------------------------------------------------------------------------
        */

        item.addEventListener(
            "mousedown",
            function(event) {

                /*
                | Prevent input blur from happening
                | before the model is selected.
                */

                event.preventDefault();


                modelInput.value =
                    model;


                modelSuggestions.innerHTML =
                    "";


                modelSuggestions.style.display =
                    "none";

            }
        );


        modelSuggestions.appendChild(
            item
        );

    });


    modelSuggestions.style.display =
        "block";
}


/*
|--------------------------------------------------------------------------
| Typing Event
|--------------------------------------------------------------------------
*/

modelInput.addEventListener(
    "input",
    function() {

        showModelSuggestions();

    }
);


/*
|--------------------------------------------------------------------------
| Focus Event
|--------------------------------------------------------------------------
*/

modelInput.addEventListener(
    "focus",
    function() {

        showModelSuggestions();

    }
);


/*
|--------------------------------------------------------------------------
| Keyboard Navigation
|--------------------------------------------------------------------------
*/

modelInput.addEventListener(
    "keydown",
    function(event) {

        const items =
            modelSuggestions.querySelectorAll(
                ".list-group-item"
            );


        if (!items.length) {
            return;
        }


        let activeIndex = -1;


        items.forEach(
            function(item, index) {

                if (
                    item.classList.contains(
                        "active"
                    )
                ) {
                    activeIndex = index;
                }

            }
        );


        /*
        |--------------------------------------------------------------------------
        | Arrow Down
        |--------------------------------------------------------------------------
        */

        if (
            event.key === "ArrowDown"
        ) {

            event.preventDefault();


            if (
                activeIndex <
                items.length - 1
            ) {

                activeIndex++;

            } else {

                activeIndex = 0;
            }


            items.forEach(
                function(item) {

                    item.classList.remove(
                        "active"
                    );

                }
            );


            items[activeIndex]
                .classList.add("active");


            items[activeIndex]
                .scrollIntoView({
                    block: "nearest"
                });

        }


        /*
        |--------------------------------------------------------------------------
        | Arrow Up
        |--------------------------------------------------------------------------
        */

        else if (
            event.key === "ArrowUp"
        ) {

            event.preventDefault();


            if (activeIndex > 0) {

                activeIndex--;

            } else {

                activeIndex =
                    items.length - 1;
            }


            items.forEach(
                function(item) {

                    item.classList.remove(
                        "active"
                    );

                }
            );


            items[activeIndex]
                .classList.add("active");


            items[activeIndex]
                .scrollIntoView({
                    block: "nearest"
                });

        }


        /*
        |--------------------------------------------------------------------------
        | Enter
        |--------------------------------------------------------------------------
        */

        else if (
            event.key === "Enter" &&
            activeIndex >= 0
        ) {

            event.preventDefault();


            modelInput.value =
                items[activeIndex]
                    .textContent;


            modelSuggestions.innerHTML =
                "";


            modelSuggestions.style.display =
                "none";
        }


        /*
        |--------------------------------------------------------------------------
        | Escape
        |--------------------------------------------------------------------------
        */

        else if (
            event.key === "Escape"
        ) {

            modelSuggestions.innerHTML =
                "";


            modelSuggestions.style.display =
                "none";
        }

    }
);


/*
|--------------------------------------------------------------------------
| Hide Suggestions When Clicking Outside
|--------------------------------------------------------------------------
*/

document.addEventListener(
    "click",
    function(event) {

        if (
            !modelInput.contains(
                event.target
            ) &&
            !modelSuggestions.contains(
                event.target
            )
        ) {

            modelSuggestions.style.display =
                "none";
        }

    }
);


/*
|--------------------------------------------------------------------------
| Brand Changed
|--------------------------------------------------------------------------
*/

brandSelect.addEventListener(
    "change",
    function() {

        const brandId =
            brandSelect.value;


        modelInput.value =
            "";


        modelSuggestions.innerHTML =
            "";


        modelSuggestions.style.display =
            "none";


        if (!brandId) {

            modelInput.disabled =
                true;


            modelInput.placeholder =
                "Select brand first...";


            availableModels = [];


            return;
        }


        loadModels(
            brandId
        );

    }
);


/*
|--------------------------------------------------------------------------
| Load Existing Search
|--------------------------------------------------------------------------
*/

<?php if ($brand_id > 0): ?>

loadModels(
    <?= (int)$brand_id ?>,
    <?= json_encode($model) ?>
);

<?php else: ?>

modelInput.disabled = true;

modelInput.placeholder =
    "Select brand first...";

<?php endif; ?>


/*
|--------------------------------------------------------------------------
| Product Image Zoom Modal
|--------------------------------------------------------------------------
*/

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


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


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


if (productImageModal) {

    productImageModal.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'
                );


            zoomedProductImage.src =
                image || '';


            zoomedProductImage.alt =
                title || '';


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


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


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

        }
    );


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

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

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

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

            } else {

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

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

        }
    );


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

            zoomedProductImage.src =
                '';

            zoomedProductImage.style.transform =
                'scale(1)';
        }
    );
}

</script>


<?php

require_once __DIR__ .
    "/partials/footer.php";

?>