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

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

$agency_id = (int)$_SESSION['user_id'];

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

function money($amt) {
    return "₹" . number_format((float)$amt, 2);
}

function bindParamsDynamic($stmt, $types, $params) {

    // ✅ FIX: agar koi parameter nahi hai to bind skip karo
    if (empty($types) || empty($params)) {
        return;
    }

    $bindNames = [];
    $bindNames[] = $types;

    for ($i = 0; $i < count($params); $i++) {
        $bindNames[] = &$params[$i];
    }

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

$search     = trim($_GET['q'] ?? '');
$start_date = trim($_GET['start_date'] ?? '');
$end_date   = trim($_GET['end_date'] ?? '');
$page       = max(1, (int)($_GET['page'] ?? 1));
$limit      = 10;
$offset     = ($page - 1) * $limit;

/* =========================
   QUICK FILTERS
========================= */
if (isset($_GET['quick'])) {
    if ($_GET['quick'] === 'today') {
        $start_date = date('Y-m-d');
        $end_date   = date('Y-m-d');
    } elseif ($_GET['quick'] === 'month') {
        $start_date = date('Y-m-01');
        $end_date   = date('Y-m-t');
    }
}

/* =========================
   WHERE CLAUSE
========================= */
$where  = "WHERE b.payment_status = 'paid'";
$params = [];
$types  = "";

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

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

if ($search !== '') {
    $where .= " AND (
        CAST(b.id AS CHAR) LIKE ? OR
        b.customer_name LIKE ? OR
        b.customer_gst LIKE ? OR
        b.phone LIKE ? OR
        u.name LIKE ?
    )";
    $like = "%{$search}%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types .= "sssss";
}

/* =========================
   EXPORT TO EXCEL
========================= */
if (isset($_GET['export']) && $_GET['export'] == '1') {
    $exportSql = "
        SELECT 
            b.id,
            b.customer_name,
            b.customer_gst,
            b.phone,
            b.subtotal,
            b.discount_percent,
            b.total_amount,
            b.payment_status,
            b.paid_amount,
            b.advance_amount,
            b.due_amount,
            b.created_at,
            u.name AS created_by_name
        FROM bills b
        LEFT JOIN users u ON b.created_by = u.id
        $where
        ORDER BY b.created_at DESC
    ";

    $stmt = $conn->prepare($exportSql);
    bindParamsDynamic($stmt, $types, $params);
    $stmt->execute();
    $res = $stmt->get_result();

    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="paid_bills_' . date('Y-m-d') . '.xls"');
    header('Pragma: no-cache');
    header('Expires: 0');

    echo "ID\tCustomer\tPhone\tGST\tSubtotal\tDiscount%\tTotal Amount\tStatus\tPaid Amount\tAdvance Amount\tDue Amount\tCreated By\tCreated At\n";

    while ($row = $res->fetch_assoc()) {
        echo (int)$row['id'] . "\t";
        echo str_replace("\t", " ", $row['customer_name'] ?: '-') . "\t";
        echo str_replace("\t", " ", $row['phone'] ?: '-') . "\t";
        echo str_replace("\t", " ", $row['customer_gst'] ?: '-') . "\t";
        echo $row['subtotal'] . "\t";
        echo $row['discount_percent'] . "\t";
        echo $row['total_amount'] . "\t";
        echo $row['payment_status'] . "\t";
        echo $row['paid_amount'] . "\t";
        echo $row['advance_amount'] . "\t";
        echo $row['due_amount'] . "\t";
        echo str_replace("\t", " ", $row['created_by_name'] ?: 'You') . "\t";
        echo $row['created_at'] . "\n";
    }
    exit;
}

/* =========================
   SUMMARY
========================= */
$summarySql = "
    SELECT 
        COUNT(*) AS total_paid_bills,
        COALESCE(SUM(b.total_amount), 0) AS total_paid_amount,
        COALESCE(AVG(b.total_amount), 0) AS avg_bill_amount,
        COALESCE(SUM(b.due_amount), 0) AS total_due_amount
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    $where
";

$summaryStmt = $conn->prepare($summarySql);
bindParamsDynamic($summaryStmt, $types, $params);
$summaryStmt->execute();
$summary = $summaryStmt->get_result()->fetch_assoc() ?: [
    'total_paid_bills'  => 0,
    'total_paid_amount' => 0,
    'avg_bill_amount'   => 0,
    'total_due_amount'  => 0
];

/* =========================
   PAGINATION COUNT
========================= */
$countSql = "
    SELECT COUNT(*) AS total
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    $where
";

$countStmt = $conn->prepare($countSql);
bindParamsDynamic($countStmt, $types, $params);
$countStmt->execute();
$totalRows = (int)($countStmt->get_result()->fetch_assoc()['total'] ?? 0);
$totalPages = max(1, (int)ceil($totalRows / $limit));

/* =========================
   MAIN DATA
========================= */
$dataSql = "
    SELECT 
        b.id,
        b.customer_name,
        b.customer_gst,
        b.phone,
        b.subtotal,
        b.discount_percent,
        b.total_amount,
        b.payment_status,
        b.created_at,
        b.paid_amount,
        b.advance_amount,
        b.due_amount,
        u.name AS created_by_name
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    $where
    ORDER BY b.created_at DESC
    LIMIT ? OFFSET ?
";

$dataStmt = $conn->prepare($dataSql);
$dataParams = $params;
$dataParams[] = $limit;
$dataParams[] = $offset;
$dataTypes = $types . "ii";
bindParamsDynamic($dataStmt, $dataTypes, $dataParams);
$dataStmt->execute();
$res = $dataStmt->get_result();

$dateSummary = "All Paid Bills";
if ($start_date !== '' && $end_date !== '') {
    $dateSummary = "From " . date('d M Y', strtotime($start_date)) . " to " . date('d M Y', strtotime($end_date));
} elseif ($start_date !== '') {
    $dateSummary = "From " . date('d M Y', strtotime($start_date));
} elseif ($end_date !== '') {
    $dateSummary = "Till " . date('d M Y', strtotime($end_date));
}
?>

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agency Paid Bills</title>
    <style>
*{
    box-sizing:border-box;
}

body{
    margin:0;
    font-family: Arial, sans-serif;
    background:#eef2f7;
    color:#1f2937;
}

/* ===== MAIN CONTAINER ===== */
.container{
    margin-left:250px;
    padding:100px 24px 24px; /* 👈 TOP SPACE FIX */
}

/* ===== CARDS ===== */
.filter-card,
.search-card,
.card{
    background:#fff;
    border-radius:18px;
    padding:18px;
    box-shadow:0 6px 20px rgba(0,0,0,0.05);
    margin-bottom:16px;
}

/* ===== TITLE ===== */
.page-title{
    font-size:20px;
    font-weight:700;
    margin-bottom:12px;
}

/* ===== DATE FILTER ===== */
.date-row{
    display:flex;
    gap:12px;
    align-items:flex-end;
    flex-wrap:wrap;
}

.field{
    flex:1;
    min-width:220px;
}

.field label{
    font-size:13px;
    font-weight:600;
    margin-bottom:6px;
    display:block;
}

/* ===== INPUTS ===== */
.date-input,
.search-box input{
    width:100%;
    height:42px;
    border:1px solid #d8e1ee;
    border-radius:10px;
    padding:0 12px;
    font-size:14px;
    outline:none;
}

.date-input:focus,
.search-box input:focus{
    border-color:#94a3b8;
}

/* ===== BUTTONS ===== */
.actions{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
}

.btn{
    height:42px;
    padding:0 16px;
    font-size:13px;
    font-weight:600;
    border-radius:999px;
    border:none;
    cursor:pointer;
    display:flex;
    align-items:center;
    justify-content:center;
    gap:6px;
}

.btn-dark{
    background:#34445d;
    color:#fff;
}

.btn-dark:hover{
    background:#25344a;
}

.btn-light{
    background:#fff;
    border:1px solid #d8e1ee;
}

.btn-light:hover{
    background:#f1f5f9;
}

/* ===== SEARCH TOP ===== */
.search-top{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
    flex-wrap:wrap;
}

.search-box{
    flex:1;
    min-width:250px;
}

/* ===== BADGES ===== */
.right-badges{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
}

.pill{
    background:#34445d;
    color:#fff;
    padding:10px 14px;
    font-size:13px;
    border-radius:999px;
    font-weight:600;
}

/* ===== EXPORT BUTTON ===== */
.export-btn{
    padding:10px 14px;
    font-size:13px;
    border-radius:999px;
    border:1px solid #d8e1ee;
    text-decoration:none;
    color:#334155;
}

.export-btn:hover{
    background:#f1f5f9;
}

/* ===== TABLE ===== */
table{
    width:100%;
    border-collapse:collapse;
}

thead th{
    background:#f3f4f6;
    padding:10px;
    font-size:13px;
    text-align:left;
    border-bottom:1px solid #e5e7eb;
}

tbody td{
    padding:10px;
    font-size:13px;
    border-bottom:1px solid #f1f5f9;
}

tbody tr:hover{
    background:#fafafa;
}

/* ===== STATUS ===== */
.pill-paid{
    background:#dcfce7;
    color:#166534;
    padding:4px 10px;
    font-size:12px;
    border-radius:999px;
    font-weight:600;
}

/* ===== ACTION BUTTON ===== */
.btn-blue{
    background:#2563eb;
    color:#fff;
    padding:6px 10px;
    font-size:12px;
    border-radius:6px;
    text-decoration:none;
}

.btn-blue:hover{
    background:#1d4ed8;
}

/* ===== PAGINATION ===== */
.pagination{
    margin-top:14px;
    display:flex;
    gap:6px;
    flex-wrap:wrap;
}

.page-link{
    padding:6px 10px;
    font-size:12px;
    border-radius:6px;
    background:#f1f5f9;
    text-decoration:none;
    color:#111;
}

.page-link.active{
    background:#0f1724;
    color:#fff;
}

/* ===== EMPTY ===== */
.empty{
    text-align:center;
    padding:18px;
    color:#6b7280;
}

/* ===== MOBILE ===== */
@media (max-width:768px){

    .container{
        margin-left:0;
        padding:12px;
    }

    .date-row{
        flex-direction:column;
    }

    .actions{
        width:100%;
        display:grid;
        grid-template-columns:1fr 1fr;
    }

    .actions .btn:last-child{
        grid-column:1/-1;
    }

    .search-top{
        flex-direction:column;
    }

    .right-badges{
        width:100%;
        display:grid;
        grid-template-columns:1fr 1fr;
    }

    .export-btn{
        grid-column:1/-1;
        text-align:center;
    }

    table thead{
        display:none;
    }

    table,
    tbody,
    tr,
    td{
        display:block;
        width:100%;
    }

    tbody tr{
        border:1px solid #e5e7eb;
        border-radius:10px;
        margin-bottom:10px;
        padding:10px;
        background:#fff;
    }

    tbody td{
        display:flex;
        justify-content:space-between;
        font-size:12px;
        padding:6px 0;
    }

    tbody td::before{
        content:attr(data-label);
        font-weight:600;
        color:#64748b;
        font-size:11px;
    }
}
.table-wrapper{
    width:100%;
    overflow-x:auto;
    border-radius:12px;
}

/* Prevent table breaking */
table{
    min-width:1000px;
}
    </style>
</head>
<body>

<div class="container">

    <div class="filter-card">
         <h1 class="page-title">Paid Bills</h1> 
        <form method="get" id="dateForm">
            <input type="hidden" name="q" value="<?= esc($search) ?>">

            <div class="date-row">
                <div class="field">
                    <label>From</label>
                    <input type="date" name="start_date" class="date-input" value="<?= esc($start_date) ?>">
                </div>

                <div class="field">
                    <label>To</label>
                    <input type="date" name="end_date" class="date-input" value="<?= esc($end_date) ?>">
                </div>

                <div class="actions">
                    <button type="submit" name="quick" value="today" class="btn btn-light">Today</button>
                    <button type="submit" name="quick" value="month" class="btn btn-light">This Month</button>
                    <button type="submit" class="btn btn-dark">🔍 Search</button>
                </div>
            </div>
        </form>
    </div>

    <div class="search-card">
        <div class="search-top">
            <div class="search-box">
                <form method="get" id="searchForm">
                    <input type="hidden" name="start_date" value="<?= esc($start_date) ?>">
                    <input type="hidden" name="end_date" value="<?= esc($end_date) ?>">

                    <input
                        type="text"
                        name="q"
                        placeholder="Search Bill No, Customer, Products"
                        value="<?= esc($search) ?>"
                        onkeyup="autoSearch()"
                    >
                </form>
            </div>

            <div class="right-badges">
                <span class="pill"><?= esc($dateSummary) ?></span>
                <span class="pill"><?= (int)$summary['total_paid_bills'] ?> bills</span>
                <a class="export-btn"
                   href="?export=1&q=<?= urlencode($search) ?>&start_date=<?= urlencode($start_date) ?>&end_date=<?= urlencode($end_date) ?>">
                     Export in Excel
                </a>
            </div>
        </div>
    </div>

    <div class="card">
       
       

       
        <div class="table-wrapper"> <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Customer</th>
                    <th>Phone</th>
                    <th>GST</th>
                    <th>Subtotal</th>
                    <th>Discount %</th>
                    <th>Total Amount</th>
                    <th>Status</th>
                    <th>Paid Amount</th>
                    <th>Created By</th>
                    <th>Created At</th>
                    <th>Invoice</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($res->num_rows > 0): ?>
                    <?php while ($row = $res->fetch_assoc()): ?>
                       <tr>
    <td data-label="ID"><?= (int)$row['id'] ?></td>
    <td data-label="Customer"><?= esc($row['customer_name'] ?: '-') ?></td>
    <td data-label="Phone"><?= esc($row['phone'] ?: '-') ?></td>
    <td data-label="GST"><?= esc($row['customer_gst'] ?: '-') ?></td>
    <td data-label="Subtotal"><?= money($row['subtotal']) ?></td>
    <td data-label="Discount %"><?= number_format((float)$row['discount_percent'], 2) ?>%</td>
    <td data-label="Total Amount"><?= money($row['total_amount']) ?></td>
    <td data-label="Status"><span class="pill-paid">Paid</span></td>
    <td data-label="Paid Amount"><?= money($row['paid_amount'] ?: $row['total_amount']) ?></td>
    <td data-label="Created By"><?= esc($row['created_by_name'] ?: 'You') ?></td>
    <td data-label="Created At"><?= date('d M Y, h:i A', strtotime($row['created_at'])) ?></td>

   <td data-label="Invoice">
    <div class="actions-row">
        <a class="btn-blue"
   href="invoice_view.php?id=<?= (int)$row['id'] ?>">
   View
</a>
    </div>
</td>
</tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="12" class="empty">No paid bills found.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
        </div>

        <div class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a class="page-link <?= $i === $page ? 'active' : '' ?>"
                   href="?page=<?= $i ?>&q=<?= urlencode($search) ?>&start_date=<?= urlencode($start_date) ?>&end_date=<?= urlencode($end_date) ?>">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
        </div>
    </div>
</div>

<script>
function autoSearch() {
    clearTimeout(window.searchTimer);
    window.searchTimer = setTimeout(function () {
        document.getElementById("searchForm").submit();
    }, 500);
}
</script>

</body>
</html>