<!----------------------------------Login------------------------------------>
<?php
include 'heade.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 সেভ করা হচ্ছে


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



// Filtering Logic
$filter = '';
$date_from = '';
$date_to = '';

if (isset($_GET['filter'])) {
    $filter = $con->real_escape_string($_GET['filter']);
}

if (isset($_GET['date_from']) && isset($_GET['date_to'])) {
    $date_from = $con->real_escape_string($_GET['date_from']);
    $date_to = $con->real_escape_string($_GET['date_to']);
}

// Pagination Logic
$limit = 10; // Number of rows per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Building the query for filtering and date range
$where_clause = "WHERE s.customer_name LIKE '%$filter%'";
if (!empty($date_from) && !empty($date_to)) {
    $where_clause .= " AND s.created_at BETWEEN '$date_from' AND '$date_to'";
}

// Fetching Sales Data
$sql = "SELECT s.id, s.customer_name, s.customer_address, s.deposit, s.discount, s.grand_total, s.created_at 
        FROM sales s 
        $where_clause
        ORDER BY s.created_at DESC 
        LIMIT $limit OFFSET $offset";

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

// Fetch Total Rows for Pagination
$totalResult = $con->query("SELECT COUNT(*) as total FROM sales s $where_clause");
$totalRows = $totalResult->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $limit);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Items Report</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border: 1px solid #ccc;
        }
        th {
            background-color: #3498db;
            color: white;
        }
        .filter, .date-filter {
            margin-bottom: 20px;
        }
        .pagination {
            margin-top: 20px;
        }
        .pagination a {
            margin: 0 5px;
            padding: 8px 12px;
            border: 1px solid #3498db;
            color: #3498db;
            text-decoration: none;
            border-radius: 4px;
        }
        .pagination a.active {
            background-color: #3498db;
            color: white;
        }
        .print-button, .row-print-button, .row-delete-button {
            padding: 8px 12px;
            background-color: #e74c3c;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .print-button:hover, .row-print-button:hover, .row-delete-button:hover {
            background-color: #c0392b;
        }
        .success-message {
            color: green;
            margin-top: 20px;
        }
    </style>
    <script>
        function printReport() {
            window.print();
        }

        function printRow(customerId) {
            window.open("invose_print.php?id=" + customerId, "_blank");
        }

        function deleteRow(id) {
            if (confirm("Are you sure you want to delete this record?")) {
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var response = JSON.parse(xhr.responseText);
                        if (response.status === 'success') {
                            alert(response.message);
                            document.getElementById("row-" + id).remove();  // Remove the row from the table
                        } else {
                            alert(response.message);
                        }
                    }
                };
                xhr.send("id=" + id + "&delete=true");  // Send the ID of the record to be deleted
            }
        }
    </script>
</head>
<body>
    <?php include 'sidebar.php';?>
    <h2>Sales Items Report</h2>
    <div class="filter">
        <form method="GET" action="">
            <input type="text" name="filter" placeholder="Search by Customer Name" value="<?php echo htmlspecialchars($filter); ?>">
            <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
            <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
            <input type="submit" value="Search">
        </form>
    </div>

    <table>
        <tr>
            <th>ID</th>
            <th>Customer Name</th>
            <th>Customer Address</th>
            <th>Deposit</th>
            <th>Discount</th>
            <th>Grand Total</th>
            <th>Date</th>
            <th>Action</th>
        </tr>

        <?php if ($result->num_rows > 0): ?>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr id="row-<?php echo $row['id']; ?>">
                    <td><?php echo $row['id']; ?></td>
                    <td><?php echo htmlspecialchars($row['customer_name']); ?></td>
                    <td><?php echo htmlspecialchars($row['customer_address']); ?></td>
                    <td><?php echo number_format($row['deposit'], 2); ?></td>
                    <td><?php echo number_format($row['discount'], 2); ?></td>
                    <td><?php echo number_format($row['grand_total'], 2); ?></td>
                    <td><?php echo date('Y-m-d', strtotime($row['created_at'])); ?></td>
                    <td>
                        <button class="bi bi-printer" onclick="printRow(<?php echo $row['id']; ?>)"></button>

                    </td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr>
                <td colspan="8">No records found</td>
            </tr>
        <?php endif; ?>
    </table>

    <div class="pagination">
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <a href="?page=<?php echo $i; ?>&filter=<?php echo urlencode($filter); ?>&date_from=<?php echo urlencode($date_from); ?>&date_to=<?php echo urlencode($date_to); ?>" class="<?php echo $i === $page ? 'active' : ''; ?>">
                <?php echo $i; ?>
            </a>
        <?php endfor; ?>
    </div>

    <button class="print-button" onclick="printReport()">Print Report</button>

    <?php
    // Handle the delete request
    if (isset($_POST['delete']) && isset($_POST['id'])) {
        $id = $_POST['id'];
        $deleteSql = "DELETE FROM sales WHERE id = $id";
        if ($con->query($deleteSql) === TRUE) {
            echo json_encode(['status' => 'success', 'message' => 'Record deleted successfully!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Error deleting record: ' . $con->error]);
        }
        exit; // Stop further script execution after sending response
    }

    $con->close();
    ?>
</body>
</html>

 

