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

include("db_connect.php");

// Notifications from other actions (optional)
$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.";

// ---------- FILTERS & PAGINATION ----------
$limit  = 10; // rows per page
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

$search_customer = isset($_GET['search_customer']) ? trim($_GET['search_customer']) : '';
$start_date      = isset($_GET['start_date']) ? trim($_GET['start_date']) : '';
$end_date        = isset($_GET['end_date']) ? trim($_GET['end_date']) : '';

// ---------- BASE QUERIES ----------
$list_sql = "
    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
";

$count_sql = "
    SELECT COUNT(*) AS total
    FROM sales s
    JOIN customers c ON s.customer_id = c.id
    WHERE 1=1
";

// ---------- BUILD FILTERS ----------
$list_types   = '';
$list_params  = [];
$count_types  = '';
$count_params = [];

// 1) Customer search: ID number (exact) OR phone (LIKE)
$search_param_list  = null;
$search_param_count = null;

if ($search_customer !== '') {
    // if numeric -> treat as national ID (exact)
    if (ctype_digit($search_customer)) {
        $list_sql  .= " AND c.id_number = ?";
        $count_sql .= " AND c.id_number = ?";

        $search_param_list  = $search_customer;
        $search_param_count = $search_customer;

        $list_types  .= 's';
        $count_types .= 's';
        $list_params[]  = $search_param_list;
        $count_params[] = $search_param_count;
    } else {
        // otherwise -> treat as phone, partial match
        $list_sql  .= " AND c.phone LIKE ?";
        $count_sql .= " AND c.phone LIKE ?";

        $search_param_list  = '%' . $search_customer . '%';
        $search_param_count = '%' . $search_customer . '%';

        $list_types  .= 's';
        $count_types .= 's';
        $list_params[]  = $search_param_list;
        $count_params[] = $search_param_count;
    }
}

// 2) Date filters on sale_datetime
if ($start_date !== '') {
    $list_sql  .= " AND s.sale_datetime >= ?";
    $count_sql .= " AND s.sale_datetime >= ?";
    $list_types  .= 's';
    $count_types .= 's';
    $list_params[]  = $start_date;
    $count_params[] = $start_date;
}

if ($end_date !== '') {
    $list_sql  .= " AND s.sale_datetime <= ?";
    $count_sql .= " AND s.sale_datetime <= ?";
    $list_types  .= 's';
    $count_types .= 's';
    $list_params[]  = $end_date;
    $count_params[] = $end_date;
}

// ORDER + LIMIT/OFFSET
$list_sql .= " ORDER BY s.sale_datetime DESC LIMIT ? OFFSET ?";
$list_types  .= 'ii';
$list_params[]  = $limit;
$list_params[]  = $offset;

// ---------- RUN LIST QUERY ----------
$list_stmt = $conn->prepare($list_sql);
if (!$list_stmt) {
    die("Error preparing list query: " . htmlspecialchars($conn->error));
}

$list_stmt->bind_param($list_types, ...$list_params);
$list_stmt->execute();
$transactions = $list_stmt->get_result();

// ---------- RUN COUNT QUERY ----------
$total_records = 0;
$count_stmt = $conn->prepare($count_sql);
if ($count_stmt) {
    if ($count_types !== '') {
        $count_stmt->bind_param($count_types, ...$count_params);
    }
    $count_stmt->execute();
    $count_res  = $count_stmt->get_result();
    $count_row  = $count_res->fetch_assoc();
    $total_records = (int)($count_row['total'] ?? 0);
    $count_stmt->close();
}

$total_pages = max(1, (int)ceil($total_records / $limit));

// Page title for head.php
$page_title = "Customer Transaction History | Admin";

// include global head
include('head.php');
?>

<body>

<?php include 'sidebar.php'; ?>

<!-- MAIN WRAPPER -->
<div class="content-wrapper" id="content-wrapper">

    <!-- TOP BAR -->
    <div class="topbar">
        <div class="topbar-left">
            <span class="menu-btn" onclick="toggleAdminSidebar()">☰</span>
            <span class="topbar-title">Admin Panel</span>
        </div>
        <div class="topbar-right">
            <button class="theme-toggle" type="button" onclick="toggleAdminTheme()">
                🌓 Theme
            </button>
            <span class="topbar-user">
                Logged in as
                <strong><?= htmlspecialchars($_SESSION['username'] ?? 'User'); ?></strong>
            </span>
        </div>
    </div>

    <!-- PAGE BODY -->
    <div class="customer-container">

        <h2>Customer Transaction History</h2>
        <p style="font-size:13px;color:var(--text-muted,#9ca3af);margin-bottom:12px;">
            Search by customer ID number or phone and filter by date range to view their purchases.
        </p>

        <?php if ($success): ?>
            <div class="message"><?= htmlspecialchars($success); ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="error"><?= htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <!-- FILTER FORM -->
        <form method="GET" class="filter-form">
            <div class="filter-row">
                <div class="filter-group">
                    <label for="search_customer">Customer ID No. / Phone</label>
                    <input
                        type="text"
                        id="search_customer"
                        name="search_customer"
                        placeholder="Enter ID number or phone"
                        value="<?= htmlspecialchars($search_customer) ?>"
                    >
                </div>

                <div class="filter-group">
                    <label for="start_date">Start date</label>
                    <input
                        type="date"
                        id="start_date"
                        name="start_date"
                        value="<?= htmlspecialchars($start_date) ?>"
                    >
                </div>

                <div class="filter-group">
                    <label for="end_date">End date</label>
                    <input
                        type="date"
                        id="end_date"
                        name="end_date"
                        value="<?= htmlspecialchars($end_date) ?>"
                    >
                </div>
            </div>

            <div class="filter-actions">
                <button type="submit" class="btn-primary">Filter</button>
                <a href="<?= htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="btn-secondary">
                    Clear filters
                </a>
            </div>
        </form>

        <h3 style="margin-top:22px;">Transactions</h3>
        <p style="font-size:13px;color:var(--text-muted,#9ca3af);">
            <?= $total_records
                ? "Showing page $page of $total_pages (" . number_format($total_records) . " records)"
                : "No transactions found for the current filters." ?>
        </p>

        <table>
            <tr>
                <th>Receipt ID</th>
                <th>Customer Name</th>
                <th>ID Number</th>
                <th>Phone</th>
                <th>Product</th>
                <th>Qty</th>
                <th>Total (KES)</th>
                <th>Sale Date</th>
            </tr>

            <?php if ($transactions && $transactions->num_rows > 0): ?>
                <?php while ($row = $transactions->fetch_assoc()): ?>
                    <tr>
                        <td><?= htmlspecialchars($row['receipt_id']) ?></td>
                        <td><?= htmlspecialchars($row['customer_name']) ?></td>
                        <td><?= htmlspecialchars($row['id_number']) ?></td>
                        <td><?= htmlspecialchars($row['phone']) ?></td>
                        <td><?= htmlspecialchars($row['product_name']) ?></td>
                        <td><?= (int)$row['quantity'] ?></td>
                        <td><?= number_format($row['total_sale'], 2) ?></td>
                        <td><?= htmlspecialchars(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.</td>
                </tr>
            <?php endif; ?>
        </table>

        <!-- 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; ?>

        <a href="admin_dashboard.php" class="btn back-btn">⬅ Return to Admin Dashboard</a>

    </div>

    <?php include 'footer.php'; ?>

</div> <!-- /content-wrapper -->

<style>
/* Main Layout */
body {
    font-family: 'Poppins', Arial, sans-serif;
    background: var(--bg-main);
    margin: 0;
    color: var(--text-main);
}

/* MAIN LAYOUT: matches other updated pages */
.content-wrapper {
    margin-left: 250px;
    padding: 25px 30px;
    background: var(--bg-main);
    min-height: 100vh;
    box-sizing: border-box;
    transition: margin-left 0.3s ease;
}

/* when sidebar is hidden, content goes full width */
.content-wrapper.fullwidth {
    margin-left: 0;
}

/* actually hide the sidebar when .hidden is applied */
#sidebar.hidden {
    display: none;
}

@media (max-width: 1000px) {
    .content-wrapper {
        margin-left: 0; /* on small screens we treat sidebar as overlay */
        padding: 20px 16px;
    }
}

.filter-group {
    display: flex;
    gap: 1rem;
    justify-content: space-between;
    margin-bottom: 20px;
}

.filter-group input {
    padding: 10px;
    width: 100%;
    background-color: var(--bg-table-head);
    border: 1px solid var(--bg-table-border);
    color: var(--text-main);
    border-radius: 5px;
    font-size: 14px;
}

.filter-group input::placeholder {
    color: var(--text-placeholder);
}

/* Make filter inputs readable in LIGHT theme */
body[data-theme="light"] .filter-group input {
    background: #ffffff;
    color: #111827;
    border-color: rgba(148, 163, 184, 0.8);
}

body[data-theme="light"] .filter-group input::placeholder {
    color: #6b7280;
}

/* Make filter labels stand out more in LIGHT theme */
body[data-theme="light"] .filter-group label {
    color: #374151;
}

/* Form */
form input {
    padding: 9px 10px;
    width: 100%;
    margin-bottom: 12px;
    border-radius: 6px;
    border: 1px solid #0a4a85;
    background: var(--bg-table-head);
    color: var(--text-main);
    font-size: 14px;
}

form input::placeholder {
    color: rgba(148,163,184,0.9);
}

form input:focus {
    outline: none;
    background: var(--bg-table-hover);
    border-color: var(--accent-gold);
}

/* Table */
table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 18px;
    background: var(--bg-card);
    color: var(--text-main);
    border-radius: 10px;
    overflow: hidden;
}

th, td {
    border: 1px solid rgba(0,0,0,0.12);
    padding: 10px 10px;
    text-align: center;
    font-size: 13px;
    white-space: nowrap;
}

body:not([data-theme="light"]) th,
body:not([data-theme="light"]) td {
    border-color: rgba(255,255,255,0.15);
}

th {
    background: var(--bg-table-head);
    color: var(--text-heading);
    font-weight: 600;
}

tbody tr {
    background: var(--bg-table-row);
}

tbody tr:nth-child(even) {
    background: var(--bg-table-row);
}

tbody tr:hover {
    background: var(--bg-table-hover);
    color: #ffffff;
}

body[data-theme="light"] tbody tr:hover {
    color: #111827;
}

/* Pagination */
.pagination {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-top: 20px;
}

.page-btn {
    padding: 8px 12px;
    background: var(--accent-gold);
    color: #fff;
    border-radius: 6px;
    cursor: pointer;
    text-decoration: none;
}

.page-btn.active {
    background: #f39c12;
}

.page-btn:hover {
    background: #e67e22;
}

/* Pagination "Clear filters" button */
.clear-filters-btn {
    background-color: #f39c12;
    padding: 10px 20px;
    color: white;
    text-decoration: none;
    border-radius: 5px;
    cursor: pointer;
}

.clear-filters-btn:hover {
    background-color: #e67e22;
}
</style>


<script>
// Sidebar toggle: hide sidebar completely and expand content
function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const wrapper = document.getElementById('content-wrapper');
    if (!sidebar || !wrapper) return;

    const isHidden = sidebar.classList.toggle('hidden');
    if (isHidden) {
        wrapper.classList.add('fullwidth');
    } else {
        wrapper.classList.remove('fullwidth');
    }
}
</script>

</body>
</html>
