<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// DB Connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "shop";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Session Info
$user_id = $_SESSION['user_id'] ?? null;
$role = $_SESSION['role'] ?? 'user';

// Pagination setup
$records_per_page = 5;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start_from = ($page - 1) * $records_per_page;

// Filters
$search_name = $_GET['search_name'] ?? '';
$search_date = $_GET['search_date'] ?? '';

// WHERE Clause
$where = [];
if ($role !== 'admin') {
    $where[] = "user_id = $user_id";
}
if (!empty($search_name)) {
    $search_name_safe = $conn->real_escape_string($search_name);
    $where[] = "customer_name LIKE '%$search_name_safe%'";
}
if (!empty($search_date)) {
    $search_date_safe = $conn->real_escape_string($search_date);
    $where[] = "DATE(created_at) = '$search_date_safe'";
}

$where_sql = count($where) > 0 ? "WHERE " . implode(' AND ', $where) : "";

// Total count for pagination
$total_sql = "SELECT COUNT(*) FROM sales $where_sql";
$total_result = $conn->query($total_sql);
$total_row = $total_result->fetch_row();
$total_records = $total_row[0];
$total_pages = ceil($total_records / $records_per_page);

// Main query
$sql = "SELECT id, customer_name, customer_address, deposit, discount, grand_total, created_at 
        FROM sales 
        $where_sql 
        ORDER BY created_at DESC 
        LIMIT $start_from, $records_per_page";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Recent Sales</title>
    <!----------------------------------Reprot Link------------------------------------>
    <?php include 'sidebar.php'; ?>
    <style>
        /* Your existing style... */
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        .pagination a {
            margin: 0 5px;
            padding: 8px 16px;
            text-decoration: none;
            color: #007bff;
            border: 1px solid #007bff;
            border-radius: 5px;
        }
        .pagination .active {
            background-color: #007bff;
            color: white;
            padding: 10px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        table, th, td {
            border: 1px solid #ccc;
        }
        th, td {
            padding: 8px;
        }
        .action-button {
            padding: 5px 10px;
            background-color: #007bff;
            color: white;
            border-radius: 5px;
            text-decoration: none;
        }
        .filter-form {
            display: flex;
            gap: 10px;
            margin: 20px 0;
        }
        .filter-form input[type="text"],
        .filter-form input[type="date"] {
            padding: 6px;
            font-size: 16px;
        }
        .filter-form button {
            padding: 6px 12px;
            font-size: 16px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
        }
        h5 {
            text-align: center;
            border-bottom: 2px solid #333;
            padding: 10px;
        }
    </style>
</head>
<body>

<h5>Sales Page</h5>
<a href="index.php">Home</a>

<!-- Filter Form -->
<form method="GET" class="filter-form">
    <input type="text" name="search_name" placeholder="Search by name" value="<?= htmlspecialchars($search_name) ?>">
    <input type="date" name="search_date" value="<?= htmlspecialchars($search_date) ?>">
    <button type="submit">Filter</button>
</form>

<!-- Sales Table -->
<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>
                <td><?= $row['id'] ?></td>
                <td><?= htmlspecialchars($row['customer_name']) ?></td>
                <td><?= htmlspecialchars($row['customer_address']) ?></td>
                <td><?= number_format($row['deposit'], 2) ?></td>
                <td><?= number_format($row['discount'], 2) ?></td>
                <td><?= number_format($row['grand_total'], 2) ?></td>
                <td><?= date('Y-m-d', strtotime($row['created_at'])) ?></td>
                <td>
                    <button class="action-button" onclick="window.open('invose_print.php?id=<?= $row['id'] ?>', '_blank')">Print</button>
                </td>
            </tr>
        <?php endwhile; ?>
    <?php else: ?>
        <tr>
            <td colspan="8">No sales found</td>
        </tr>
    <?php endif; ?>
</table>

<!-- Pagination -->
<div class="pagination">
    <?php
    // Preserve filters in pagination links
    $queryStr = http_build_query([
        'search_name' => $search_name,
        'search_date' => $search_date
    ]);
    ?>
    <?php if ($page > 1): ?>
        <a href="?<?= $queryStr ?>&page=<?= $page - 1 ?>">Prev</a>
    <?php endif; ?>

    <span class="active">Page <?= $page ?> of <?= $total_pages ?></span>

    <?php if ($page < $total_pages): ?>
        <a href="?<?= $queryStr ?>&page=<?= $page + 1 ?>">Next</a>
    <?php endif; ?>
</div>

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

