<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'cashier') {
    header("Location: login.php");
    exit();
}

include("db_connect.php");

// Notifications
$success = "";
$error   = "";

if (isset($_GET['added']))   $success = "Customer added successfully!";
if (isset($_GET['updated'])) $success = "Customer updated successfully!";
if (isset($_GET['deleted'])) $success = "Customer deleted successfully!";
if (isset($_GET['error']))   $error   = "Please fill in all fields.";

// Pagination settings
$limit  = 10; // 10 entries per page
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

// Get total number of sales for the customer
$total_records = 0;
$customer_id   = null;
$search_customer = isset($_GET['search_customer']) ? trim($_GET['search_customer']) : '';
$start_date    = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date      = isset($_GET['end_date']) ? $_GET['end_date'] : '';

// Construct base query to fetch customer transaction history
$query = "
    SELECT s.*, p.name AS product_name, c.customer_name, c.phone, c.id_number
    FROM sales s
    JOIN products p ON s.product_id = p.id
    JOIN customers c ON s.customer_id = c.id
    WHERE 1=1
";

// Add customer search filter (ID or phone)
if ($search_customer !== '') {
    if (is_numeric($search_customer)) {
        // If customer search is numeric (ID), use equality comparison for exact match
        $query .= " AND c.id_number = ?";
    } else {
        // For phone number, use LIKE to match partial values
        $query .= " AND c.phone LIKE ?";
        $search_customer = "%" . $search_customer . "%"; // Add wildcard for partial match
    }
}

// Add date filters
if ($start_date !== '') {
    $query .= " AND s.sale_datetime >= ?";
}
if ($end_date !== '') {
    $query .= " AND s.sale_datetime <= ?";
}

// Combine filters into pagination query
$query .= " ORDER BY s.sale_datetime DESC LIMIT $limit OFFSET $offset";

// Prepare query
if ($stmt = $conn->prepare($query)) {
    $types = '';
    $bindings = [];

    if ($search_customer !== '') {
        if (is_numeric($search_customer)) {
            $types .= 's'; // Bind as string for ID search
        } else {
            $types .= 's'; // Bind as string for phone search
        }
        $bindings[] = $search_customer;
    }
    if ($start_date !== '') {
        $types .= 's';
        $bindings[] = $start_date;
    }
    if ($end_date !== '') {
        $types .= 's';
        $bindings[] = $end_date;
    }

    if (!empty($types)) {
        $stmt->bind_param($types, ...$bindings);
    }

    $stmt->execute();
    $result = $stmt->get_result();

    // Count the total records for pagination
    $count_query = "SELECT COUNT(*) AS total FROM sales s JOIN customers c ON s.customer_id = c.id WHERE 1=1";
    if ($search_customer !== '') {
        if (is_numeric($search_customer)) {
            $count_query .= " AND c.id_number = ?";
        } else {
            $count_query .= " AND c.phone LIKE ?";
        }
    }
    if ($start_date !== '') {
        $count_query .= " AND s.sale_datetime >= ?";
    }
    if ($end_date !== '') {
        $count_query .= " AND s.sale_datetime <= ?";
    }
    $count_stmt = $conn->prepare($count_query);

    $count_bindings = [];
    $count_types = '';
    if ($search_customer !== '') {
        if (is_numeric($search_customer)) {
            $count_types .= 's'; // Bind as string for ID search
        } else {
            $count_types .= 's'; // Bind as string for phone search
        }
        $count_bindings[] = $search_customer;
    }
    if ($start_date !== '') {
        $count_types .= 's';
        $count_bindings[] = $start_date;
    }
    if ($end_date !== '') {
        $count_types .= 's';
        $count_bindings[] = $end_date;
    }

    if (!empty($count_types)) {
        $count_stmt->bind_param($count_types, ...$count_bindings);
    }

    $count_stmt->execute();
    $count_result = $count_stmt->get_result();
    $count_row = $count_result->fetch_assoc();
    $total_records = (int)($count_row['total'] ?? 0);
    $count_stmt->close();

    $total_pages = max(1, (int)ceil($total_records / $limit));
} else {
    $error = "Error preparing query: " . $conn->error;
}

$page_title = "Customer Transaction History | Cashier POS";
$active     = 'transactions'; // for top-nav highlight
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <link rel="stylesheet" href="cashier_customer_details.css">
</head>
<body>

<div class="cashier-shell">
    <?php include "cashier_sidebar.php"; ?>

    <main class="cashier-main">
        <!-- Topbar with nav + theme toggle (consistent with dashboard) -->
        <div class="cashier-topbar">
            <div class="cashier-topbar-left">
                <h1><?= htmlspecialchars($page_title) ?></h1>
                <small>Search and view customer transaction history.</small>
            </div>

            <div class="cashier-topbar-right">
                <nav class="cashier-topnav">
                    <a href="cashier_dashboard.php" class="<?= ($active === 'dashboard') ? 'active' : '' ?>">Dashboard</a>
                    <a href="record_sales.php" class="<?= ($active === 'sales') ? 'active' : '' ?>">Sales</a>
                    <a href="cashier_view_daily_sales.php" class="<?= ($active === 'daily_sales') ? 'active' : '' ?>">Today’s Sales</a>
                    <a href="transaction_history.php" class="<?= ($active === 'transactions') ? 'active' : '' ?>">Transactions</a>
                    <a href="customers.php" class="<?= ($active === 'customers') ? 'active' : '' ?>">Customers</a>
                </nav>

                <button type="button" class="cashier-theme-toggle" onclick="toggleCashierTheme()">
                    <span class="icon">🌓</span>
                    <span class="label">Theme</span>
                </button>

                <button class="cashier-toggle" onclick="toggleCashierSidebar()">☰</button>
            </div>
        </div>

        <!-- Transaction History Section -->
        <section class="pos-card">
            <div class="pos-card-header">
                <h2>Customer Transaction History</h2>
                <p>Search by customer ID, phone, and filter by date range.</p>
            </div>

            <!-- Filter Form -->
            <form method="GET" class="filter-form">
                <label for="search_customer">Search by Customer ID or Phone:</label>
                <input type="text" name="search_customer" id="search_customer" value="<?= htmlspecialchars($search_customer) ?>">

                <label for="start_date">Start Date:</label>
                <input type="date" name="start_date" id="start_date" value="<?= htmlspecialchars($start_date) ?>">

                <label for="end_date">End Date:</label>
                <input type="date" name="end_date" id="end_date" value="<?= htmlspecialchars($end_date) ?>">

                <button type="submit" class="btn-primary">Filter</button>

                <!-- Clear Button -->
                <a href="cashier_customer_details.php" class="btn-clear">Clear Filters</a>
            </form>

            <!-- Display Messages -->
            <?php if ($success): ?>
                <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <!-- Transactions Table -->
            <div class="pos-table-card">
                <div class="pos-table-header">
                    <div>
                        <h3>Transactions</h3>
                        <p>Showing <?= $total_records ? "page $page of $total_pages" : "no transactions found." ?></p>
                    </div>
                    <span class="badge-muted">
                        Total transactions: <?= number_format($total_records) ?>
                    </span>
                </div>

                <div class="pos-table-wrapper">
                    <table class="pos-table">
                        <thead>
                            <tr>
                                <th>Receipt ID</th>
                                <th>Customer Name</th>
                                <th>Phone</th>
                                <th>ID Number</th>
                                <th>Product</th>
                                <th>Quantity</th>
                                <th>Amount</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($result && $result->num_rows > 0): ?>
                                <?php while ($row = $result->fetch_assoc()): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($row['receipt_id']) ?></td>
                                        <td><?= htmlspecialchars($row['customer_name']) ?></td>
                                        <td><?= htmlspecialchars($row['phone']) ?></td>
                                        <td><?= htmlspecialchars($row['id_number']) ?></td>
                                        <td><?= htmlspecialchars($row['product_name']) ?></td>
                                        <td><?= (int)$row['quantity'] ?></td>
                                        <td><?= number_format($row['total_sale'], 2) ?></td>
                                        <td><?= date('Y-m-d H:i', strtotime($row['sale_datetime'])) ?></td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="8" class="empty-row">No transactions found for this customer.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <a href="?page=<?= $i ?>&search_customer=<?= urlencode($search_customer) ?>&start_date=<?= urlencode($start_date) ?>&end_date=<?= urlencode($end_date) ?>"
                               class="page-btn <?= ($i == $page) ? 'active' : '' ?>">
                                <?= $i ?>
                            </a>
                        <?php endfor; ?>
                    </div>
                <?php endif; ?>
            </div>

            <div style="margin-top: 14px;">
                <a href="cashier_dashboard.php" class="back-link">← Back to dashboard</a>
            </div>
        </section>
    </main>
</div>

<script>
function toggleCashierSidebar() {
    const sidebar = document.getElementById('cashierSidebar');
    if (sidebar) {
        sidebar.classList.toggle('is-collapsed');
    }
}
</script>

</body>
</html>
