<?php

session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once "../config/database.php";


/* UPDATE ORDER STATUS */

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

    $order_id = (int)($_POST["order_id"] ?? 0);

    $status = $_POST["status"] ?? "";
    $tracking_number = trim($_POST["tracking_number"] ?? "");

    $delivery_charge = (float)($_POST["delivery_charge"] ?? 0);

    $allowed_statuses = [
        "Pending",
        "Confirmed",
        "Delivered",
        "Cancelled"
    ];


    if (
        $order_id > 0 &&
        in_array($status, $allowed_statuses, true)
    ) {

       $stmt = $conn->prepare(
    "UPDATE orders
    SET status = ?,
        tracking_number = ?,
        total_amount = (
            SELECT COALESCE(SUM(price * quantity), 0)
            FROM order_items
            WHERE order_id = orders.id
        ) + ?,
        delivery_charge = ?
    WHERE id = ?"
);


        if (!$stmt) {

            die(
                "Database Error: " .
                $conn->error
            );

        }


       $stmt->bind_param(
    "ssddi",
    $status,
    $tracking_number,
    $delivery_charge,
    $delivery_charge,
    $order_id
);


        if (!$stmt->execute()) {

            die(
                "Update Error: " .
                $stmt->error
            );

        }


        $stmt->close();


        header(
            "Location: manage-orders.php?updated=1&order_id=" .
            $order_id
        );

        exit;
    }
}


/* GET ALL ORDERS */

$sql = "
    SELECT *
    FROM orders
    ORDER BY order_date DESC
";


$result = $conn->query($sql);


if (!$result) {

    die(
        "Database Error: " .
        $conn->error
    );

}

?>


<!DOCTYPE html>
<html lang="en">


<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Manage Orders - Muthu Jewellers
    </title>


    <style>

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }


        body {
            font-family: Arial, sans-serif;
            background: #f5f5f5;
            color: #111;
        }


        header {
            background: #111;
            color: white;

            padding: 25px 40px;

            display: flex;
            justify-content: space-between;
            align-items: center;
        }


        header h2 {
            font-size: 30px;
        }


        .back-btn {
            background: #b8860b;
            color: white;

            text-decoration: none;

            padding: 12px 20px;

            border-radius: 7px;

            font-size: 16px;
        }


        .container {
            max-width: 1500px;

            margin: 40px auto;

            padding: 20px;
        }


        h1 {
            font-size: 38px;
            margin-bottom: 30px;
        }


        .success-message {
            background: #d4edda;

            color: #155724;

            border: 1px solid #c3e6cb;

            padding: 15px 20px;

            border-radius: 8px;

            margin-bottom: 25px;

            font-size: 17px;

            font-weight: bold;
        }


        .orders-box {
            background: white;

            border-radius: 15px;

            padding: 25px;

            box-shadow:
                0 4px 15px rgba(0,0,0,0.08);

            overflow-x: auto;
        }


        table {
            width: 100%;

            border-collapse: collapse;

            min-width: 1250px;
        }


        th {
            background: #111;

            color: white;

            padding: 14px;

            text-align: left;
        }


        td {
            padding: 14px;

            border-bottom: 1px solid #ddd;

            vertical-align: top;
        }


        tr:hover {
            background: #f9f9f9;
        }


        .amount {
            font-weight: bold;

            color: #b8860b;

            white-space: nowrap;
        }


        /* PRODUCTS */

        .product-list {
            display: flex;

            flex-direction: column;

            gap: 15px;
        }


        .product-item {
            display: flex;

            gap: 15px;

            align-items: center;

            min-width: 300px;
        }


        .product-item img {
            width: 85px;

            height: 85px;

            object-fit: cover;

            border-radius: 10px;

            border: 1px solid #ddd;
        }


        .product-details {
            line-height: 1.6;
        }


        .product-name {
            font-size: 17px;

            font-weight: bold;
        }


        .product-colour {
            color: #555;
        }


        .status-form {
            display: flex;

            gap: 8px;

            align-items: center;
        }


        .status-select {
            padding: 9px 10px;

            border: 1px solid #ccc;

            border-radius: 6px;

            font-size: 14px;

            background: white;
        }
.tracking-input {
    padding: 9px 10px;
    border: 1px solid #ccc;
    border-radius: 6px;
    font-size: 14px;
    width: 170px;
    background: white;
}

        .update-btn {
            background: #111;

            color: white;

            border: none;

            padding: 9px 12px;

            border-radius: 6px;

            cursor: pointer;
        }


        .update-btn:hover {
            background: #b8860b;
        }


        .no-orders {
            text-align: center;

            padding: 40px;

            font-size: 20px;

            color: #777;
        }


        @media (max-width: 700px) {

            header {
                flex-direction: column;

                gap: 15px;

                text-align: center;
            }


            h1 {
                font-size: 30px;
            }

        }

    </style>

</head>


<body>


<header>

    <h2>
        MUTHU JEWELLERS 💎
    </h2>


    <a
        href="dashboard.php"
        class="back-btn"
    >
        ← Dashboard
    </a>

</header>


<div class="container">


    <h1>
        📦 Manage Orders
    </h1>


    <?php if (isset($_GET["updated"])): ?>

        <div class="success-message">

            Order #<?= (int)$_GET["order_id"] ?>
            status updated successfully.

        </div>

    <?php endif; ?>


    <div class="orders-box">


        <?php if ($result && $result->num_rows > 0): ?>


            <table>


                <thead>

                    <tr>

                        <th>
                            Order ID
                        </th>

                        <th>
                            Customer Name
                        </th>

                        <th>
                            Phone 1
                        </th>

                        <th>
                            Phone 2
                        </th>

                        <th>
                            Address
                        </th>

                        <th>
                            Nearest City
                        </th>

                        <th>
                            Products
                        </th>

                        <th>
                            Total
                        </th>

                        <th>
                            Order Date
                        </th>

                        <th>
                            Status
                        </th>

                    </tr>

                </thead>


                <tbody>


                <?php while ($order = $result->fetch_assoc()): ?>


                    <tr>


                        <td>

                            #<?= (int)$order["id"] ?>

                        </td>


                        <td>

                            <?= htmlspecialchars(
                                $order["customer_name"]
                            ) ?>

                        </td>


                        <td>

                            <?= htmlspecialchars(
                                $order["phone1"]
                            ) ?>

                        </td>


                        <td>

                            <?= htmlspecialchars(
                                $order["phone2"]
                            ) ?>

                        </td>


                        <td>

                            <?= nl2br(
                                htmlspecialchars(
                                    $order["address"]
                                )
                            ) ?>

                        </td>


                        <td>

                            <?= htmlspecialchars(
                                $order["city"]
                            ) ?>

                        </td>


                        <td>


                            <div class="product-list">


                            <?php

                            $order_id =
                                (int)$order["id"];


                            $item_sql = "
                                SELECT *
                                FROM order_items
                                WHERE order_id = ?
                            ";


                            $item_stmt =
                                $conn->prepare(
                                    $item_sql
                                );


                            $item_stmt->bind_param(
                                "i",
                                $order_id
                            );


                            $item_stmt->execute();


                            $item_result =
                                $item_stmt->get_result();


                            ?>


                            <?php while (
                                $item =
                                $item_result->fetch_assoc()
                            ): ?>


                                <div class="product-item">


                                    <?php
                                    if (
                                        !empty(
                                            $item["image"]
                                        )
                                    ):
                                    ?>

                                        <img
                                            src="../assets/images/<?=
                                            htmlspecialchars(
                                                $item["image"]
                                            )
                                            ?>"
                                            alt="<?=
                                            htmlspecialchars(
                                                $item["product_name"]
                                            )
                                            ?>"
                                        >

                                    <?php endif; ?>


                                    <div
                                        class="product-details"
                                    >


                                        <div
                                            class="product-name"
                                        >

                                            <?= htmlspecialchars(
                                                $item[
                                                    "product_name"
                                                ]
                                            ) ?>

                                        </div>


                                        <div
                                            class="product-colour"
                                        >

                                            Colour:

                                            <strong>

                                                <?= htmlspecialchars(
                                                    $item["colour"]
                                                ) ?>

                                            </strong>

                                        </div>


                                        <div>

                                            Quantity:

                                            <?= (int)
                                                $item[
                                                    "quantity"
                                                ] ?>

                                        </div>


                                        <div>

                                            Price:

                                            Rs.

                                            <?= number_format(
                                                $item["price"],
                                                2
                                            ) ?>

                                        </div>


                                    </div>


                                </div>


                            <?php endwhile; ?>


                            <?php
                            $item_stmt->close();
                            ?>


                            </div>


                        </td>


                        <td class="amount">

                            Rs.

                            <?= number_format(
                                $order["total_amount"],
                                2
                            ) ?>

                        </td>


                        <td>

                            <?= htmlspecialchars(
                                $order["order_date"]
                            ) ?>

                        </td>


                        <td>


                            <form
                                method="POST"
                                class="status-form"
                            >


                                <input
                                    type="hidden"
                                    name="order_id"
                                    value="<?=
                                        (int)$order["id"]
                                    ?>"
                                >


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


                                    <option
                                        value="Pending"
                                        <?=
                                        $order["status"]
                                        === "Pending"
                                        ? "selected"
                                        : ""
                                        ?>
                                    >
                                        Pending
                                    </option>


                                    <option
                                        value="Confirmed"
                                        <?=
                                        $order["status"]
                                        === "Confirmed"
                                        ? "selected"
                                        : ""
                                        ?>
                                    >
                                        Confirmed
                                    </option>


                                    <option
                                        value="Delivered"
                                        <?=
                                        $order["status"]
                                        === "Delivered"
                                        ? "selected"
                                        : ""
                                        ?>
                                    >
                                        Delivered
                                    </option>


                                    <option
                                        value="Cancelled"
                                        <?=
                                        $order["status"]
                                        === "Cancelled"
                                        ? "selected"
                                        : ""
                                        ?>
                                    >
                                        Cancelled
                                    </option>


                                </select>

                                <input
                                type="text"
                                name="tracking_number"
                                class="tracking-input"
                                placeholder="Fardar Tracking No."
                                value="<?= htmlspecialchars($order["tracking_number"] ?? "") ?>"
>
                                <input
    type="number"
    name="delivery_charge"
    class="tracking-input"
    placeholder="Delivery Charge"
    step="0.01"
    min="0"
    value="<?= htmlspecialchars($order["delivery_charge"] ?? "0") ?>"
>

                                <button
                                    type="submit"
                                    class="update-btn"
                                >
                                    Update
                                </button>


                            </form>


                        </td>


                    </tr>


                <?php endwhile; ?>


                </tbody>


            </table>


        <?php else: ?>


            <div class="no-orders">

                📦 No orders found.

            </div>


        <?php endif; ?>


    </div>


</div>


</body>

</html>