<?php
session_start();
require_once '../config.php';

// Check admin login
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$adminName = $_SESSION['name'] ?? 'Admin';

// Filters
$from = isset($_GET['from']) ? trim($_GET['from']) : '';
$to   = isset($_GET['to']) ? trim($_GET['to']) : '';

// Basic date validation
if ($from !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) {
    $from = '';
}
if ($to !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
    $to = '';
}

// Pagination
$perPage = 15;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;

// Build query safely
$where = "1";
$params = [];
$types = "";

if ($from !== '') {
    $where .= " AND DATE(created_at) >= ?";
    $params[] = $from;
    $types .= "s";
}

if ($to !== '') {
    $where .= " AND DATE(created_at) <= ?";
    $params[] = $to;
    $types .= "s";
}

function bind_stmt_params(mysqli_stmt $stmt, string $types, array $params): void
{
    if ($types === '' || empty($params)) {
        return;
    }

    $bind = [$types];
    foreach ($params as $k => $v) {
        $bind[$k + 1] = &$params[$k];
    }

    call_user_func_array([$stmt, 'bind_param'], $bind);
}

function e($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function build_url(array $extra = []): string
{
    $query = array_merge($_GET, $extra);
    foreach ($query as $k => $v) {
        if ($v === '' || $v === null) {
            unset($query[$k]);
        }
    }
    return '?' . http_build_query($query);
}

$rangeText = 'All records';
if ($from && $to) {
    $rangeText = date('d M Y', strtotime($from)) . ' to ' . date('d M Y', strtotime($to));
} elseif ($from) {
    $rangeText = 'From ' . date('d M Y', strtotime($from));
} elseif ($to) {
    $rangeText = 'Up to ' . date('d M Y', strtotime($to));
}

// Summary query
$summarySql = "
    SELECT 
        COUNT(*) AS total_bills,
        COALESCE(SUM(total_amount), 0) AS total_sales,
        COALESCE(SUM(paid_amount), 0) AS total_paid,
        COALESCE(SUM(due_amount), 0) AS total_due
    FROM bills
    WHERE $where
";
$stmt = mysqli_prepare($conn, $summarySql);
if (!$stmt) {
    die('Summary query failed: ' . mysqli_error($conn));
}
bind_stmt_params($stmt, $types, $params);
mysqli_stmt_execute($stmt);
$summaryResult = mysqli_stmt_get_result($stmt);
$data = mysqli_fetch_assoc($summaryResult) ?: [
    'total_bills' => 0,
    'total_sales' => 0,
    'total_paid'  => 0,
    'total_due'   => 0,
];
mysqli_stmt_close($stmt);

// Total rows for pagination
$countSql = "
    SELECT COUNT(*) AS total_rows
    FROM bills
    WHERE $where
";
$stmtCount = mysqli_prepare($conn, $countSql);
if (!$stmtCount) {
    die('Count query failed: ' . mysqli_error($conn));
}
bind_stmt_params($stmtCount, $types, $params);
mysqli_stmt_execute($stmtCount);
$countResult = mysqli_stmt_get_result($stmtCount);
$totalRows = (int)(mysqli_fetch_assoc($countResult)['total_rows'] ?? 0);
mysqli_stmt_close($stmtCount);

$totalPages = max(1, (int)ceil($totalRows / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
}
$offset = ($page - 1) * $perPage;

// List query with pagination
$listSql = "
    SELECT id, customer_name, total_amount, paid_amount, due_amount, created_at
    FROM bills
    WHERE $where
    ORDER BY id ASC
    LIMIT ? OFFSET ?
";
$stmt2 = mysqli_prepare($conn, $listSql);
if (!$stmt2) {
    die('List query failed: ' . mysqli_error($conn));
}

$listTypes = $types . "ii";
$listParams = $params;
$listParams[] = $perPage;
$listParams[] = $offset;
bind_stmt_params($stmt2, $listTypes, $listParams);

mysqli_stmt_execute($stmt2);
$listResult = mysqli_stmt_get_result($stmt2);

$rows = [];
if ($listResult) {
    while ($r = mysqli_fetch_assoc($listResult)) {
        $rows[] = $r;
    }
}
mysqli_stmt_close($stmt2);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Custom Report</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
:root{
    --bg:#f4f6f9;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#6b7280;
    --line:#e5e7eb;
    --primary:#374155;
    --primary-soft:#eef2f7;
    --success:#16a34a;
    --warning:#f59e0b;
    --danger:#ef4444;
    --info:#2563eb;
    --violet:#7c3aed;
    --shadow:0 14px 36px rgba(15,23,42,.08);
    --radius:20px;
    --sidebar-width:260px;
    --header-height:70px;
}

*{
    box-sizing:border-box;
}

html, body{
    max-width:100%;
    overflow-x:hidden;
}

body{
    margin:0;
    font-family:Inter, Arial, Helvetica, sans-serif;
    background:
        radial-gradient(circle at top left, rgba(55,65,85,.08), transparent 30%),
        radial-gradient(circle at bottom right, rgba(37,99,235,.06), transparent 28%),
        var(--bg);
    color:var(--text);
}

header{
    position:fixed;
    top:0;
    left:var(--sidebar-width);
    right:0;
    height:var(--header-height);
    z-index:1000;
}
.sidebar{
    position:fixed;
    top:0;
    left:0;
    width:var(--sidebar-width);
    height:100vh;
    z-index:1001;
}
.page-wrap{
    position:relative;
    margin-left:var(--sidebar-width);
    min-height:100vh;
    padding-top:calc(var(--header-height) + 10px) !important;
    padding-left:14px !important;
    padding-right:14px !important;
    padding-bottom:14px !important;
    width:calc(100% - var(--sidebar-width));
}

.wrap{
    max-width:1600px;
    margin:0 auto;
}

.report-header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:16px;
    margin-bottom:14px;
    padding:14px;
    background:linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
    border:1px solid var(--line);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    flex-wrap:wrap;
}

.title-block{
    display:flex;
    flex-direction:column;
    gap:6px;
}

.title-block h1{
    margin:0;
    font-size:20px;
    color:var(--primary);
    font-weight:900;
    letter-spacing:-.04em;
    display:flex;
    align-items:center;
    gap:12px;
}

.title-block h1 i{
    width:42px;
    height:42px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
       background:#eef2f7 !important;
    color:#374155 !important;
    border-radius:12px;
    box-shadow:none;
}

.title-block p{
    margin:0;
    font-size:12px;
    color:var(--muted);
    line-height:1.5;
}

.user-pill{
    display:flex;
    align-items:center;
    gap:10px;
    background:#f9fafb;
    border:1px solid var(--line);
    border-radius:999px;
    padding:10px 14px;
    white-space:nowrap;
}

.avatar{
    width:34px;
    height:34px;
    border-radius:50%;
    display:grid;
    place-items:center;
    background:#111;
    color:#fff;
    font-weight:700;
    font-size:13px;
}

.panel{
    background:var(--card);
    border:1px solid var(--line);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    padding:14px;
}

.filter-bar{
    display:flex;
    flex-wrap:wrap;
    align-items:end;
    justify-content:space-between;
    gap:10px;
    margin-bottom:14px;
}

.filter-left{
    display:flex;
    flex-wrap:wrap;
    gap:12px;
    align-items:end;
}

.field{
    display:flex;
    flex-direction:column;
    gap:6px;
}

.field label{
    font-size:11px;
    color:var(--muted);
    font-weight:800;
    letter-spacing:.06em;
    text-transform:uppercase;
}

input[type="date"],
    

button,
.btn-link{
    height:34px;
    padding:0 10px !important;
    border-radius:10px !important;
    border:1px solid var(--line);
    font-size:12px;
    outline:none;
    transition:.2s ease;
}

input[type="date"]{
    height:34px !important;
    font-size:12px !important;
    background:#fff;
    padding:0 12px;
    min-width:170px;
    color:#111827;
}

input[type="date"]:focus{
    border-color:#374155;
    box-shadow:0 0 0 3px rgba(55,65,85,.08);
}

button,
.btn-link{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    cursor:pointer;
    padding:0 16px;
    text-decoration:none;
    font-weight:700;
}

.btn-primary{
    background:linear-gradient(135deg, #111827, #374155);
    color:#fff;
    border:none;
    box-shadow:0 10px 18px rgba(17,24,39,.14);
}

.btn-primary:hover{
    transform:translateY(-1px);
    box-shadow:0 14px 24px rgba(17,24,39,.18);
}

.btn-secondary{
    background:#fff;
    color:#111827;
}

.btn-secondary:hover{
    background:#f8fafc;
}

/* summary cards */
.cards{
    display:grid;
    grid-template-columns:repeat(4, minmax(0,1fr));
    gap:12px;
    margin-top:8px;
}

.card{
    position:relative;
    overflow:hidden;
    background:#fff;
    border:1px solid var(--line);
    border-radius:16px;
    padding:12px;
    box-shadow:0 8px 24px rgba(0,0,0,.04);
    min-height:auto !important;
    transition:.2s ease;
}

.cards .card:hover{
    transform:translateY(-2px);
    box-shadow:0 14px 28px rgba(15,23,42,.08);
}

.card .icon{
    width:36px;
    height:36px;
    border-radius:12px;
    display:flex;
    align-items:center;
    justify-content:center;
    background:#eef2f7;
    color:#374155;
    font-size:14px;
    margin-bottom:10px;
    box-shadow:0 4px 10px rgba(0,0,0,.05);
}

.card h3{
    margin:0;
    font-size:11px;
    color:var(--muted);
    font-weight:800;
    text-transform:uppercase;
    letter-spacing:.08em;
}

.card .value{
    margin-top:8px;
    font-size:18px;
    font-weight:900;
    color:var(--primary);
    line-height:1.1;
    word-break:break-word;
}

.cards .card:nth-child(1) .value{ color:var(--primary); }
.cards .card:nth-child(2) .value{ color:var(--info); }
.cards .card:nth-child(3) .value{ color:var(--success); }
.cards .card:nth-child(4) .value{ color:var(--danger); }

.cards .card:nth-child(1) .icon{ background:rgba(55,65,85,.08); color:var(--primary); }
.card .icon i{
    color:#374155 !important;
}

.subtext{
    margin-top:6px;
    color:var(--muted);
    font-size:11px;
}

.section-head{
    display:flex;
    justify-content:space-between;
    align-items:flex-end;
    gap:12px;
    margin:20px 0 12px;
    flex-wrap:wrap;
}

.section-head h2{
    margin:0;
    font-size:16px;
    font-weight:900;
    color:#111827;
    display:flex;
    align-items:center;
    gap:10px;
}

.section-head h2 i{
    color:#374155;
    background:#eef2f7;
    padding:6px;
    border-radius:8px;
}

.section-head p{
    margin:4px 0 0;
    color:var(--muted);
    font-size:12px;
}

.report-tools{
    display:flex;
    align-items:center;
    gap:12px;
    flex-wrap:wrap;
    margin-bottom:14px;
}

.search-box{
    display:flex;
    align-items:center;
    gap:10px;
    flex:1 1 340px;
    background:#fff;
    border:1px solid var(--line);
    border-radius:14px;
    padding:8px 12px;
    box-shadow:0 2px 6px rgba(0,0,0,0.03);
}

.search-box i{
    color:#374155;
    font-size:14px;
}

.search-box input{
    width:100%;
    border:none;
    outline:none;
    font-size:12px;
    color:#111827;
    background:transparent;
}

.table-wrap{
    overflow:auto;
    border:1px solid var(--line);
    border-radius:18px;
    background:#fff;
    box-shadow:0 8px 24px rgba(0,0,0,.04);
}

table{
    width:100%;
    border-collapse:collapse;
    min-width:860px;
}

thead th{
    background:#f8fafc;
    color:#334155;
    font-size:11px;
    text-align:left;
    padding:8px;
    border-bottom:1px solid var(--line);
    font-weight:800;
}

tbody td{
    padding:8px;
    border-bottom:1px solid #f1f5f9;
    font-size:12px;
    color:#111827;
}

tbody tr:hover{
    background:#fafafa;
}

.amount{
    font-weight:800;
    color:#0f172a;
}

.amount.sales{
    color:var(--info);
}

.amount.paid{
    color:var(--success);
}

.amount.due{
    color:var(--danger);
}

.empty{
    padding:24px;
    text-align:center;
    color:var(--muted);
}

.pagination{
    display:flex;
    justify-content:center;
    flex-wrap:wrap;
    gap:8px;
    margin-top:18px;
}

.page-btn{
    min-width:32px;
    height:32px;
    padding:0 12px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:10px;
    border:1px solid var(--line);
    background:#fff;
    color:#111827;
    text-decoration:none;
    font-size:12px;
    font-weight:700;
    transition:.2s ease;
}

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

.page-btn.active{
    background:var(--primary);
    color:#fff;
    border-color:var(--primary);
}

.summary-row{
    display:grid;
    grid-template-columns:repeat(3, minmax(0,1fr));
    gap:16px;
    margin-top:18px;
}

.summary-box{
    background:linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
    border:1px solid var(--line);
    border-radius:18px;
    padding:12px;
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
}

.summary-box strong{
    color:#334155;
    font-size:12px;
}

.summary-box span{
    font-weight:900;
    color:var(--info);
    font-size:13px;
}

@media (max-width: 1100px){
    .cards{
        grid-template-columns:repeat(2, minmax(0,1fr));
    }

    .summary-row{
        grid-template-columns:1fr;
    }
}

@media (max-width: 900px){
    .page-wrap{
        margin-left:0;
        padding:16px;
    }
}

@media (max-width: 640px){
    .cards{
        grid-template-columns:1fr;
    }

    .panel{
        padding:16px;
    }

    .report-header{
        padding:16px;
    }

    .title-block h1{
        font-size:22px;
    }

    input[type="date"],
    button,
    .btn-link{
        width:100%;
    }

    .filter-left{
        width:100%;
    }

    .field{
        width:100%;
    }

    .field input[type="date"]{
        width:100%;
        min-width:unset;
    }
}
/* ================= MOBILE RESPONSIVE FIX ================= */
@media (max-width: 768px) {

    /* HEADER FIX */
    body {
        padding-top: 70px;
    }

    header {
        left: 0 !important;
        width: 100%;
    }

    /* SIDEBAR REMOVE SPACE */
    .page-wrap {
        margin-left: 0 !important;
        width: 100% !important;
        padding: 12px !important;
    }

    .wrap {
        width: 100%;
        max-width: 100%;
    }

    /* HEADER SECTION */
    .report-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
        padding: 12px;
    }

    .title-block h1 {
        font-size: 18px;
    }

    .title-block p {
        font-size: 12px;
    }

    /* FILTER SECTION */
    .filter-bar {
        flex-direction: column;
        align-items: stretch;
        gap: 10px;
    }

    .filter-left {
        flex-direction: column;
        width: 100%;
        gap: 10px;
    }

    .field {
        width: 100%;
    }

    .field input {
        width: 100%;
    }

    button,
    .btn-link {
        width: 100%;
        justify-content: center;
    }

    /* CARDS */
    .cards {
        grid-template-columns: 1fr;
        gap: 10px;
    }

    .card {
        padding: 12px;
    }

    .card .value {
        font-size: 18px;
    }

    /* SEARCH */
    .search-box {
        width: 100%;
    }

    /* TABLE SCROLL (IMPORTANT) */
    .table-wrap {
        overflow-x: auto;
        width: 100%;
    }

    table {
        min-width: 750px; /* 👈 main fix */
    }

    th, td {
        font-size: 12px;
        padding: 8px;
        white-space: nowrap;
    }

    /* PAGINATION */
    .pagination {
        flex-wrap: wrap;
        justify-content: center;
        gap: 6px;
    }

    .page-btn {
        font-size: 11px;
        padding: 6px 10px;
    }
}
    </style>
</head>
<body>

<?php include 'adminsidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="page-wrap">
    <div class="wrap">

        <div class="report-header">
            <div class="title-block">
                <h1><i class="fa-solid fa-file-lines"></i> Custom Reports</h1>
                <p>Report range: <?php echo e($rangeText); ?></p>
            </div>
        </div>

        <div class="panel">
            <form method="GET" class="filter-bar">
                <div class="filter-left">
                    <div class="field">
                        <label for="from">From Date</label>
                        <input type="date" name="from" id="from" value="<?php echo e($from); ?>">
                    </div>

                    <div class="field">
                        <label for="to">To Date</label>
                        <input type="date" name="to" id="to" value="<?php echo e($to); ?>">
                    </div>

                    <button type="submit" class="btn-primary">
                        <i class="fa-solid fa-filter"></i> Filter
                    </button>

                    <a href="custom_reports.php" class="btn-link btn-secondary">
                        <i class="fa-solid fa-rotate-left"></i> Reset
                    </a>
                </div>
            </form>

            <div class="cards">
                <div class="card">
                    <div class="icon"><i class="fa-solid fa-file-invoice"></i></div>
                    <h3>Total Bills</h3>
                    <div class="value"><?php echo number_format((float)$data['total_bills']); ?></div>
                    <div class="subtext">All bills in selected range</div>
                </div>

                <div class="card">
                    <div class="icon"><i class="fa-solid fa-indian-rupee-sign"></i></div>
                    <h3>Total Sales</h3>
                    <div class="value">₹ <?php echo number_format((float)$data['total_sales'], 2); ?></div>
                    <div class="subtext">Gross billing amount</div>
                </div>

                <div class="card">
                    <div class="icon"><i class="fa-solid fa-circle-check"></i></div>
                    <h3>Paid</h3>
                    <div class="value">₹ <?php echo number_format((float)$data['total_paid'], 2); ?></div>
                    <div class="subtext">Collected amount</div>
                </div>

                <div class="card">
                    <div class="icon"><i class="fa-solid fa-clock"></i></div>
                    <h3>Due</h3>
                    <div class="value">₹ <?php echo number_format((float)$data['total_due'], 2); ?></div>
                    <div class="subtext">Outstanding balance</div>
                </div>
            </div>

            <div class="section-head">
                <div>
                    <h2><i class="fa-solid fa-receipt"></i> Bill Records</h2>
                    <p>Showing <?php echo (int)min($perPage, max(0, $totalRows - $offset)); ?> of <?php echo (int)$totalRows; ?> records on this page</p>
                </div>
            </div>

            <div class="report-tools">
                <div class="search-box">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <input type="text" id="liveSearch" placeholder="Live search by id, customer, amount or date...">
                </div>
            </div>

            <div class="table-wrap">
                <table id="reportTable">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Customer</th>
                            <th>Total</th>
                            <th>Paid</th>
                            <th>Due</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($rows)): ?>
                            <?php foreach ($rows as $row): ?>
                                <tr data-search="<?php echo e(strtolower(
                                    $row['id'] . ' ' .
                                    $row['customer_name'] . ' ' .
                                    $row['total_amount'] . ' ' .
                                    $row['paid_amount'] . ' ' .
                                    $row['due_amount'] . ' ' .
                                    $row['created_at']
                                )); ?>">
                                    <td><?php echo e($row['id']); ?></td>
                                    <td><?php echo e($row['customer_name']); ?></td>
                                    <td class="amount sales">₹ <?php echo number_format((float)$row['total_amount'], 2); ?></td>
                                    <td class="amount paid">₹ <?php echo number_format((float)$row['paid_amount'], 2); ?></td>
                                    <td class="amount due">₹ <?php echo number_format((float)$row['due_amount'], 2); ?></td>
                                    <td><?php echo date('d M Y', strtotime($row['created_at'])); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr id="emptyRow">
                                <td colspan="6" class="empty">No bills found for the selected date range.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a class="page-btn" href="<?php echo e(build_url(['page' => $page - 1])); ?>">&laquo;</a>
                    <?php endif; ?>

                    <?php
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);

                    if ($startPage > 1) {
                        echo '<a class="page-btn" href="' . e(build_url(['page' => 1])) . '">1</a>';
                        if ($startPage > 2) {
                            echo '<span class="page-btn" style="pointer-events:none;">...</span>';
                        }
                    }

                    for ($p = $startPage; $p <= $endPage; $p++):
                    ?>
                        <a class="page-btn <?php echo $p === $page ? 'active' : ''; ?>" href="<?php echo e(build_url(['page' => $p])); ?>">
                            <?php echo $p; ?>
                        </a>
                    <?php endfor;

                    if ($endPage < $totalPages) {
                        if ($endPage < $totalPages - 1) {
                            echo '<span class="page-btn" style="pointer-events:none;">...</span>';
                        }
                        echo '<a class="page-btn" href="' . e(build_url(['page' => $totalPages])) . '">' . $totalPages . '</a>';
                    }
                    ?>

                    <?php if ($page < $totalPages): ?>
                        <a class="page-btn" href="<?php echo e(build_url(['page' => $page + 1])); ?>">&raquo;</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
(function () {
    const searchInput = document.getElementById('liveSearch');
    const table = document.getElementById('reportTable');
    const emptyRow = document.getElementById('emptyRow');

    if (!searchInput || !table) return;

    const rows = Array.from(table.querySelectorAll('tbody tr')).filter(row => row.id !== 'emptyRow');

    searchInput.addEventListener('input', function () {
        const q = this.value.toLowerCase().trim();
        let visibleCount = 0;

        rows.forEach(row => {
            const text = row.getAttribute('data-search') || '';
            const show = text.includes(q);
            row.style.display = show ? '' : 'none';
            if (show) visibleCount++;
        });

        if (emptyRow) {
            emptyRow.style.display = visibleCount === 0 ? '' : 'none';
            if (visibleCount === 0) {
                emptyRow.querySelector('td').textContent = 'No matching bills found.';
            } else {
                emptyRow.querySelector('td').textContent = 'No bills found for the selected date range.';
            }
        } else if (visibleCount === 0) {
            const tbody = table.querySelector('tbody');
            const tr = document.createElement('tr');
            tr.id = 'emptyRow';
            tr.innerHTML = '<td colspan="6" class="empty">No matching bills found.</td>';
            tbody.appendChild(tr);
        }
    });
})();
</script>

</body>
</html>