
<!----------------------------------Login------------------------------------>
<?php
session_start();
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role = $_SESSION['role']; // ✅ এখানে role সেভ করা হচ্ছে
$userId = $_SESSION['user_id'];


$isAdmin = ($_SESSION['role'] == 'admin');

?>

<?php
include 'php/db_connection.php';
include 'sidebar.php';
include 'heade.php';

$itemsPerPage = 5; // প্রতি পেইজে কতটি অর্ডার দেখানো হবে
$page = isset($_GET['page']) ? $_GET['page'] : 1; // বর্তমান পেইজ
$offset = ($page - 1) * $itemsPerPage; // OFFSET হিসাব করা

if (isset($_GET['customer_phone'])) {
    $customerPhone = $_GET['customer_phone'];
    
    // Prepare the query to search for the customer by phone
    $stmt = mysqli_prepare($con, 'SELECT * FROM customer WHERE Customer_phone = ?');
    mysqli_stmt_bind_param($stmt, 's', $customerPhone);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if (mysqli_num_rows($result) > 0) {
        $customer = mysqli_fetch_assoc($result);
        echo "<h2>Customer History for " . htmlspecialchars($customer['Customer_name']) . "</h2>";
        echo "<p>Phone: " . htmlspecialchars($customer['Customer_phone']) . "</p>";
        echo "<p>Address: " . htmlspecialchars($customer['Customer_address']) . "</p>";

        // Query to get orders associated with this customer
        $customerId = $customer['Customer_phone'];
        $orderStmt = mysqli_prepare($con, 'SELECT * FROM sales WHERE Customer_phone = ? LIMIT ? OFFSET ?');
        mysqli_stmt_bind_param($orderStmt, 'sii', $customerId, $itemsPerPage, $offset);
        mysqli_stmt_execute($orderStmt);
        $orderResult = mysqli_stmt_get_result($orderStmt);

        if (mysqli_num_rows($orderResult) > 0) {
            echo "<h3>Order History</h3>";
            echo "<table border='1' style='width: 100%; border-collapse: collapse;'>
                    <tr>
                        <th>Date</th>
                        <th>Customer Name</th>
                        <th>Order ID</th>
                        <th>Grand Total</th>
                        <th>Collected</th>
                        <th>Final amount</th>
                        <th>Change</th>
                        <th>discount</th>
                        <th>Action</th>
                    </tr>";

            $totalGrandTotal = 0;  // Total Grand Amount
            $totalDeposit = 0;     // Total Deposit
            $totaldiscount = 0;     // Total Deposit
            while ($order = mysqli_fetch_assoc($orderResult)) {
                echo "<tr>
                        <td>" . htmlspecialchars($order['created_at']) . "</td>
                        <td>" . htmlspecialchars($order['customer_name']) . "</td>
                        <td>" . htmlspecialchars($order['id']) . "</td>
                        <td>" . htmlspecialchars($order['grand_total']) . "</td>
                        <td>" . htmlspecialchars($order['collected']) . "</td>
                        <td>" . htmlspecialchars($order['final_amount']) . "</td>
                        <td>" . htmlspecialchars($order['change']) . "</td>
                        <td>" . htmlspecialchars($order['discount']) . "</td>
                        <td><a href='?order_id=" . urlencode($order['id']) . "'>View Details</a></td>
                      </tr>";
                
                // Calculate total grand total and total deposit
                $totalGrandTotal += $order['grand_total'];
                $totalDeposit += $order['final_amount'];
                $totaldiscount += $order['discount'];
            }

            // Calculate remaining amount
            $remainingAmount = $totalGrandTotal - $totalDeposit- $totaldiscount ;

            // Display the total row with Grand Total, Deposit, and Remaining Amount
            echo "<tr>
                    <td colspan='5' style='text-align: right;'><strong>Total Amount</strong></td>
                    <td><strong>" . htmlspecialchars($totalGrandTotal) . "</strong></td>
                  </tr>
                  <tr>
                  <td colspan='5' style='text-align: right;'><strong>Deposit:</strong></td>
                  <td><strong> " . htmlspecialchars($totalDeposit) . "</strong></td>
                  </tr>
                  <td colspan='5' style='text-align: right;'><strong>Discount:</strong></td>
                  <td><strong> " . htmlspecialchars($totaldiscount) . "</strong></td>
                  </tr>
                  <tr>
                  <td colspan='5' style='text-align: right;'><strong>Remaining: </strong></td>
                  <td><strong> " . htmlspecialchars($remainingAmount) . "</strong></td>
                  </tr>
                  ";
            echo "</table>";

            // Pagination: Total number of pages
            $totalOrdersQuery = mysqli_query($con, "SELECT COUNT(*) AS total_orders FROM sales WHERE Customer_phone = '$customerId'");
            $totalOrders = mysqli_fetch_assoc($totalOrdersQuery)['total_orders'];
            $totalPages = ceil($totalOrders / $itemsPerPage);

            // Pagination buttons
            echo "<div class='pagination'>";
            if ($page > 1) {
                echo "<a href='?customer_phone=$customerPhone&page=" . ($page - 1) . "'>&laquo; Previous</a>";
            }
            for ($i = 1; $i <= $totalPages; $i++) {
                echo "<a href='?customer_phone=$customerPhone&page=$i' " . ($i == $page ? "class='active'" : "") . ">$i</a> ";
            }
            if ($page < $totalPages) {
                echo "<a href='?customer_phone=$customerPhone&page=" . ($page + 1) . "'>Next &raquo;</a>";
            }
            echo "</div>";
            
        } else {
            echo "<p>No orders found for this customer.</p>";
        }
    } else {
        echo "<p>No customer found with this phone number.</p>";
    }
} else {
    echo "<p>Customer phone number is required.</p>";
}

// Check for order details
if (isset($_GET['order_id'])) {
    $orderId = $_GET['order_id'];
    
    // Prepare and execute query to get order details
    $orderStmt = mysqli_prepare($con, "SELECT * FROM sales WHERE id = ?");
    mysqli_stmt_bind_param($orderStmt, 'i', $orderId);
    mysqli_stmt_execute($orderStmt);
    $orderResult = mysqli_stmt_get_result($orderStmt);
    $order = mysqli_fetch_assoc($orderResult);

    if ($order) {
        echo "<h2>Order Details for Order ID: " . htmlspecialchars($order['id']) . "</h2>";
        echo "<p>Customer Name: " . htmlspecialchars($order['customer_name']) . "</p>";
        echo "<p>Customer Address: " . htmlspecialchars($order['customer_address']) . "</p>";
        echo "<p>Deposit: " . htmlspecialchars($order['deposit']) . "</p>";
        echo "<p>Discount: " . htmlspecialchars($order['discount']) . "</p>";
        echo "<p>Grand Total: " . htmlspecialchars($order['grand_total']) . "</p>";
        echo "<p>Date: " . htmlspecialchars($order['created_at']) . "</p>";

        // Query to get items for the specific order
        $itemsStmt = mysqli_prepare($con, "SELECT * FROM sales_items WHERE sales_id = ?");
        mysqli_stmt_bind_param($itemsStmt, 'i', $orderId);
        mysqli_stmt_execute($itemsStmt);
        $itemsResult = mysqli_stmt_get_result($itemsStmt);

        if (mysqli_num_rows($itemsResult) > 0) {
            echo "<h3>Order Items</h3>";
            echo "<table border='1' style='width: 100%; border-collapse: collapse;'>
                    <tr>
                        <th>Product ID</th>
                        <th>Description</th>
                        <th>Quantity</th>
                        <th>Price</th>
                        <th>Total</th>
                    </tr>";
            while ($item = mysqli_fetch_assoc($itemsResult)) {
                echo "<tr>
                        <td>" . htmlspecialchars($item['id']) . "</td>
                        <td>" . htmlspecialchars($item['product_description']) . "</td>
                        <td>" . htmlspecialchars($item['quantity']) . "</td>
                        <td>" . htmlspecialchars($item['price']) . "</td>
                        <td>" . htmlspecialchars($item['total']) . "</td>
                      </tr>";
            }
            echo "</table>";
        } else {
            echo "<p>No items found for this order.</p>";
        }
    } else {
        echo "<p>No order found with this ID.</p>";
    }
}
?>

<style>
    .pagination {
        display: flex;
        justify-content: center;
        margin-top: 20px;
    }
    .pagination a {
        padding: 8px 16px;
        margin: 0 5px;
        background-color: #3498db;
        color: white;
        text-decoration: none;
        border-radius: 5px;
    }
    .pagination a:hover {
        background-color: #2980b9;
    }
    .pagination a.active {
        background-color: #2ecc71;
    }
</style>

