<?php 
require('connection.inc.php');
require('security.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Function to check if the user has the required permission
function hasPermission($role_id, $permission_name, $conn) {
    $query = "SELECT rp.role_permissions_id
              FROM role_permissions rp
              INNER JOIN permissions p ON rp.permission_id = p.permission_id
              WHERE rp.role_id = ? AND p.permission_name = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("is", $role_id, $permission_name); // Binding parameters (integer and string)
    $stmt->execute();
    $result = $stmt->get_result();

    return $result->num_rows > 0; // Return true if permission exists
}

// Get user's role from session
$user_role_id = $_SESSION['role_id'];

// Define the required permission for this page
$permission_name = "Orders"; 
// Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

// OPTIONAL: If you want to allow only admins (e.g., role_id == 1)
if ($_SESSION['role_id'] != 1) {
    echo "Access denied. Only admin can view orders.";
    exit();
}

$order_id = $_GET['order_id'];

// Fetch order details
$order_stmt = $conn->prepare("
    SELECT order_id, first_name, last_name, email, phone, country, address, city, state, postcode,
           subtotal, payment_method, status, payment_status, payment_id, payment_datetime, created_at
    FROM orders
    WHERE order_id = ?
");
$order_stmt->bind_param("s", $order_id);
$order_stmt->execute();
$order_result = $order_stmt->get_result();

if ($order_result->num_rows === 0) {
    echo "Order not found.";
    exit();
}

$order = $order_result->fetch_assoc();

// Fetch ordered items with product and unit info
$items_stmt = $conn->prepare("
    SELECT oi.product_id, p.product_name, oi.unit_id, pu.unit_name,
           oi.quantity, oi.unit_price, oi.total_price, pi.product_img
    FROM order_items oi
    INNER JOIN products p ON oi.product_id = p.product_id
    INNER JOIN product_units pu ON oi.unit_id = pu.unit_id
    LEFT JOIN product_imgs pi ON oi.product_id = pi.product_id
    WHERE oi.order_id = ?
    GROUP BY oi.product_id
");
$items_stmt->bind_param("s", $order_id);
$items_stmt->execute();
$items_result = $items_stmt->get_result();
?>

<!DOCTYPE html>
<html lang="zxx">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Management Admin</title>

    <link rel="icon" href="img/mini_logo.png" type="image/png">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap1.min.css" />
    <!-- themefy CSS -->
    <link rel="stylesheet" href="vendors/themefy_icon/themify-icons.css" />
    <!-- select2 CSS -->
    <link rel="stylesheet" href="vendors/niceselect/css/nice-select.css" />
    <!-- owl carousel CSS -->
    <link rel="stylesheet" href="vendors/owl_carousel/css/owl.carousel.css" />
    <!-- gijgo css -->
    <link rel="stylesheet" href="vendors/gijgo/gijgo.min.css" />
    <!-- font awesome CSS -->
    <link rel="stylesheet" href="vendors/font_awesome/css/all.min.css" />
    <link rel="stylesheet" href="vendors/tagsinput/tagsinput.css" />

    <!-- date picker -->
     <link rel="stylesheet" href="vendors/datepicker/date-picker.css" />

     <link rel="stylesheet" href="vendors/vectormap-home/vectormap-2.0.2.css" />
     
     <!-- scrollabe  -->
     <link rel="stylesheet" href="vendors/scroll/scrollable.css" />
    <!-- datatable CSS -->
    <link rel="stylesheet" href="vendors/datatable/css/jquery.dataTables.min.css" />
    <link rel="stylesheet" href="vendors/datatable/css/responsive.dataTables.min.css" />
    <link rel="stylesheet" href="vendors/datatable/css/buttons.dataTables.min.css" />
    <!-- text editor css -->
    <link rel="stylesheet" href="vendors/text_editor/summernote-bs4.css" />
    <!-- morris css -->
    <link rel="stylesheet" href="vendors/morris/morris.css">
    <!-- metarial icon css -->
    <link rel="stylesheet" href="vendors/material_icon/material-icons.css" />

    <!-- menu css  -->
    <link rel="stylesheet" href="css/metisMenu.css">
    <!-- style CSS -->
    <link rel="stylesheet" href="css/style1.css" />
    <link rel="stylesheet" href="css/colors/default.css" id="colorSkinCSS">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Add SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.5.6/dist/sweetalert2.min.css" rel="stylesheet">

    <!-- Add SweetAlert2 JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.5.6/dist/sweetalert2.min.js"></script>
<style>
.active_status {
    color: green;
    font-weight: bold;
}
.inactive_status {
    background: red !important;
    font-weight: bold;
}

    .card h2, .card h4 {
        color: #2c3e50;
    }

    .badge-warning {
        background-color: #f1c40f;
        color: #000;
    }




        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #f0f0f0; }

</style>

</head>
<body class="crm_body_bg">
<?php
// Your PHP code for checking permission goes here
if (!hasPermission($user_role_id, $permission_name, $conn)) {
    // Destroy the session to log the user out
    session_unset(); // Unset all session variables
    session_destroy(); // Destroy the session

    // Show SweetAlert and then redirect
    echo "<script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'error',
                title: 'Access Denied',
                text: 'You do not have permission to access this page.',
                showConfirmButton: false,
                timer: 3000
            }).then(function() {
                window.location.href = 'index.php'; // Redirect after the alert
            });
        });
    </script>";
    exit();
}
?>


<!-- main content part here -->
 
 <!-- sidebar  -->
 <?php require('sidebar.inc.php'); ?>
 <!--/ sidebar  -->


<section class="main_content dashboard_part large_header_bg">
    <!-- menu  -->
        <?php require('header.inc.php'); ?>
    <!--/ menu  -->
  
<div class="main_content_iner overly_inner py-4">
    <div class="container-fluid">
        <div class="card shadow-lg p-4">
            <h2 class="mb-4">Order Details</h2>

            <div class="mb-3">
                <h5 class="text-muted">Order ID: <span class="fw-bold"><?= htmlspecialchars($order['order_id']) ?></span></h5>
                <p><strong>Customer:</strong> <?= htmlspecialchars($order['first_name'] . ' ' . $order['last_name']) ?></p>
                <p><strong>Email:</strong> <?= htmlspecialchars($order['email']) ?></p>
                <p><strong>Phone:</strong> <?= htmlspecialchars($order['phone']) ?></p>
                <p><strong>Address:</strong> <?= htmlspecialchars($order['address'] . ', ' . $order['city'] . ', ' . $order['state'] . ', ' . $order['postcode'] . ', ' . $order['country']) ?></p>
                <p><strong>Order Date:</strong> <?= date("d-m-Y H:i", strtotime($order['created_at'])) ?></p>
                <p><strong>Payment Method:</strong> <?= htmlspecialchars($order['payment_method']) ?></p>
                <p><strong>Payment Status:</strong> 
                    <span class="badge bg-<?= ($order['payment_status'] == 'Paid') ? 'success' : 'warning' ?>">
                        <?= htmlspecialchars($order['payment_status']) ?>
                    </span>
                </p>
                <?php if ($order['payment_id']): ?>
                    <p><strong>Payment ID:</strong> <?= htmlspecialchars($order['payment_id']) ?></p>
                    <p><strong>Payment Date:</strong> <?= date("d-m-Y H:i", strtotime($order['payment_datetime'])) ?></p>
                <?php endif; ?>
                <p><strong>Subtotal:</strong> ₹<?= number_format($order['subtotal'], 2) ?></p>

                <!-- Edit Order Status Form -->
                <form method="post" action="update_order_status.php">
                    <input type="hidden" name="order_id" value="<?= htmlspecialchars($order['order_id']) ?>">
                    <div class="mb-3">
                        <label for="status" class="form-label"><strong>Update Order Status:</strong></label>
                        <select name="status" id="status" class="form-select" required>
                            <option value="">--Select Status--</option>
                            <option value="Pending" <?= ($order['status'] == 'Pending') ? 'selected' : '' ?>>Pending</option>
                            <option value="Processing" <?= ($order['status'] == 'Processing') ? 'selected' : '' ?>>Processing</option>
                            <option value="Shipped" <?= ($order['status'] == 'Shipped') ? 'selected' : '' ?>>Shipped</option>
                            <option value="Delivered" <?= ($order['status'] == 'Delivered') ? 'selected' : '' ?>>Delivered</option>
                            <option value="Cancelled" <?= ($order['status'] == 'Cancelled') ? 'selected' : '' ?>>Cancelled</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">Update Status</button>
                </form>
            </div>

            <h4 class="mt-5 mb-3">Ordered Items</h4>
            <div class="table-responsive">
                <table class="table table-bordered align-middle text-center">
                    <thead class="table-dark">
                        <tr>
                            <th>Image</th>
                            <th>Product</th>
                            <th>Unit</th>
                            <th>Quantity</th>
                            <th>Unit Price (₹)</th>
                            <th>Total (₹)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        mysqli_data_seek($items_result, 0); // Reset pointer
                        while ($item = $items_result->fetch_assoc()):
                            // Fetch image for product
                            $img_stmt = $conn->prepare("SELECT product_img FROM product_imgs WHERE product_id = ? LIMIT 1");
                            $img_stmt->bind_param("i", $item['product_id']);
                            $img_stmt->execute();
                            $img_result = $img_stmt->get_result();
                            $img_row = $img_result->fetch_assoc();
                            $product_img = $img_row ? $img_row['product_img'] : 'placeholder.png';
                        ?>
                            <tr>
                                <td><img src="<?= htmlspecialchars($product_img) ?>" alt="Image" style="width: 60px; height: auto;"></td>
                                <td><?= htmlspecialchars($item['product_name']) ?></td>
                                <td><?= htmlspecialchars($item['unit_name']) ?></td>
                                <td><?= htmlspecialchars($item['quantity']) ?></td>
                                <td><?= number_format($item['unit_price'], 2) ?></td>
                                <td><?= number_format($item['total_price'], 2) ?></td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>



</section>

<!-- footer part -->
<?php require('footer.inc.php'); ?>
<!-- main content part end -->


<div id="back-top" style="display: none;">
    <a title="Go to Top" href="#">
        <i class="ti-angle-up"></i>
    </a>
</div>

<!-- footer  -->
<script src="js/jquery1-3.4.1.min.js"></script>
<!-- popper js -->
<script src="js/popper1.min.js"></script>
<!-- bootstarp js -->
<script src="js/bootstrap1.min.js"></script>
<!-- sidebar menu  -->
<script src="js/metisMenu.js"></script>
<!-- waypoints js -->
<script src="vendors/count_up/jquery.waypoints.min.js"></script>
<!-- waypoints js -->
<script src="vendors/chartlist/Chart.min.js"></script>
<!-- counterup js -->
<script src="vendors/count_up/jquery.counterup.min.js"></script>

<!-- nice select -->
<script src="vendors/niceselect/js/jquery.nice-select.min.js"></script>
<!-- owl carousel -->
<script src="vendors/owl_carousel/js/owl.carousel.min.js"></script>

<!-- responsive table -->
<script src="vendors/datatable/js/jquery.dataTables.min.js"></script>
<script src="vendors/datatable/js/dataTables.responsive.min.js"></script>
<script src="vendors/datatable/js/dataTables.buttons.min.js"></script>
<script src="vendors/datatable/js/buttons.flash.min.js"></script>
<script src="vendors/datatable/js/jszip.min.js"></script>
<script src="vendors/datatable/js/pdfmake.min.js"></script>
<script src="vendors/datatable/js/vfs_fonts.js"></script>
<script src="vendors/datatable/js/buttons.html5.min.js"></script>
<script src="vendors/datatable/js/buttons.print.min.js"></script>

<!-- datepicker  -->
<script src="vendors/datepicker/datepicker.js"></script>
<script src="vendors/datepicker/datepicker.en.js"></script>
<script src="vendors/datepicker/datepicker.custom.js"></script>

<script src="js/chart.min.js"></script>
<script src="vendors/chartjs/roundedBar.min.js"></script>

<!-- progressbar js -->
<script src="vendors/progressbar/jquery.barfiller.js"></script>
<!-- tag input -->
<script src="vendors/tagsinput/tagsinput.js"></script>
<!-- text editor js -->
<script src="vendors/text_editor/summernote-bs4.js"></script>

<script src="js/custom.js"></script>
<script>
    $(document).on('click', '.status_btn', function(e) {
    e.preventDefault();

    var $btn = $(this);
    var productId = $btn.data('id');
    var currentStatus = $btn.data('status');
    var newStatus = currentStatus == 1 ? 0 : 1;
    var csrfToken = $btn.data('csrf');
 console.log({
        id: productId,
        status: newStatus,
        csrf_token: csrfToken
    });

    $.ajax({
        url: 'update_product_status.php',
        type: 'POST',
        data: {
            id: productId,
            status: newStatus,
            csrf_token: csrfToken
        },
        success: function(response) {
            console.log("Response from server:", response); // log response
            if (response === 'success') {
                $btn.data('status', newStatus);
                $btn.text(newStatus == 1 ? 'Active' : 'Inactive');
                $btn.toggleClass('active_status inactive_status');
            } else {
                alert('Status update failed.');
            }
        }
    });
});

</script>
</body>

<!-- Mirrored from demo.dashboardpack.com/user-management-html/add_new_user.html by HTTrack Website Copier/3.x [XR&CO'2014], Mon, 02 Dec 2024 05:54:56 GMT -->
</html>
