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

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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo "Access Denied";
    exit;
}

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

function money($v) {
    return number_format((float)$v, 2, '.', ',');
}

function fmt_date($d) {
    return !empty($d) ? date('d M Y', strtotime($d)) : '-';
}

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

$q              = trim($_GET['q'] ?? '');
$status         = trim($_GET['status'] ?? 'all');
$date_from      = trim($_GET['date_from'] ?? '');
$date_to        = trim($_GET['date_to'] ?? '');
$range          = trim($_GET['range'] ?? '');
$page           = max(1, (int)($_GET['page'] ?? 1));
$limit          = 10;
$offset         = ($page - 1) * $limit;

/* quick date ranges */
$today = date('Y-m-d');
$monthStart = date('Y-m-01');

if ($range === 'today') {
    $date_from = $today;
    $date_to   = $today;
} elseif ($range === 'month') {
    $date_from = $monthStart;
    $date_to   = $today;
}

/* where clause */
$where = "WHERE 1=1";

if ($q !== '') {
    $s = $conn->real_escape_string($q);
    $where .= " AND (
        CAST(b.id AS CHAR) LIKE '%{$s}%'
        OR b.customer_name LIKE '%{$s}%'
        OR b.customer_gst LIKE '%{$s}%'
        OR b.phone LIKE '%{$s}%'
        OR u.name LIKE '%{$s}%'
    )";
}

if ($status !== '' && $status !== 'all') {
    $statusEsc = $conn->real_escape_string($status);
    $where .= " AND b.payment_status = '{$statusEsc}'";
}

if ($date_from !== '') {
    $df = $conn->real_escape_string($date_from);
    $where .= " AND DATE(b.created_at) >= '{$df}'";
}

if ($date_to !== '') {
    $dt = $conn->real_escape_string($date_to);
    $where .= " AND DATE(b.created_at) <= '{$dt}'";
}

/* export csv */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $sql = "
        SELECT
            b.id,
            b.customer_name,
            b.customer_gst,
            b.phone,
            b.subtotal,
            b.taxable_amount,
            b.sgst_amount,
            b.cgst_amount,
            b.total_amount,
            b.payment_status,
            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, b.id DESC
    ";

    $result = $conn->query($sql);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=invoices_' . date('Ymd_His') . '.csv');

    $out = fopen('php://output', 'w');
    fputcsv($out, [
        'Invoice No', 'Customer', 'GST', 'Phone', 'Created By', 'Status',
        'Subtotal', 'Taxable', 'SGST', 'CGST', 'Total', 'Advance', 'Due', 'Date'
    ]);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            fputcsv($out, [
                $row['id'],
                $row['customer_name'],
                $row['customer_gst'],
                $row['phone'],
                $row['created_by_name'],
                $row['payment_status'],
                $row['subtotal'],
                $row['taxable_amount'],
                $row['sgst_amount'],
                $row['cgst_amount'],
                $row['total_amount'],
                $row['advance_amount'],
                $row['due_amount'],
                $row['created_at'],
            ]);
        }
    }

    fclose($out);
    exit;
}

/* summary */
$summarySql = "
    SELECT
        COUNT(*) AS total_invoices,
        COALESCE(SUM(CASE WHEN b.payment_status='paid' THEN 1 ELSE 0 END),0) AS paid_count,
        COALESCE(SUM(CASE WHEN b.payment_status='unpaid' THEN 1 ELSE 0 END),0) AS unpaid_count,
        COALESCE(SUM(CASE WHEN b.payment_status='advance' THEN 1 ELSE 0 END),0) AS advance_count,
        COALESCE(SUM(b.total_amount),0) AS total_sales,
        COALESCE(SUM(b.due_amount),0) AS due_sum
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    {$where}
";
$summaryRes = $conn->query($summarySql);
$summary = $summaryRes ? $summaryRes->fetch_assoc() : [
    'total_invoices' => 0,
    'paid_count' => 0,
    'unpaid_count' => 0,
    'advance_count' => 0,
    'total_sales' => 0,
    'due_sum' => 0
];

/* pagination count */
$countSql = "
    SELECT COUNT(*) AS total_rows
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    {$where}
";
$countRes = $conn->query($countSql);
$totalRows = $countRes ? (int)($countRes->fetch_assoc()['total_rows'] ?? 0) : 0;
$totalPages = max(1, (int)ceil($totalRows / $limit));

/* invoice list */
$listSql = "
    SELECT
        b.id,
        b.customer_name,
        b.customer_gst,
        b.phone,
        b.subtotal,
        b.taxable_amount,
        b.sgst_amount,
        b.cgst_amount,
        b.total_amount,
        b.payment_status,
        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, b.id DESC
    LIMIT {$limit} OFFSET {$offset}
";
$listRes = $conn->query($listSql);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Invoices</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
    body{
        background:#eef2f7;
        font-family:'Segoe UI',Arial,sans-serif;
        margin:0;
        color:#0f172a;
    }
    .main-content{
        margin-left:250px;
        padding:18px;
    }
    .page-card{
        background:#fff;
        border:1px solid rgba(148,163,184,.15);
        border-radius:18px;
        box-shadow:0 8px 26px rgba(15,23,42,.06);
        padding:22px;
    }
    .header-row{
        display:flex;
        justify-content:space-between;
        align-items:flex-start;
        gap:16px;
        flex-wrap:wrap;
        margin-bottom:18px;
    }
    .page-title{
        display:flex;
        align-items:center;
        gap:10px;
        font-size:28px;
        font-weight:800;
        margin:0;
        color:#000;
    }
    .page-subtitle{
        color:#64748b;
        margin-top:4px;
    }
    .top-actions{
        display:flex;
        gap:10px;
        flex-wrap:wrap;
        align-items:center;
    }
    .btn-pill{
        border-radius:999px;
        padding:10px 16px;
        font-weight:700;
        display:inline-flex;
        align-items:center;
        gap:8px;
        text-decoration:none;
    }
    .btn-dark-pill{
        background:#334155;
        color:#fff;
        border:1px solid #334155;
    }
    .btn-dark-pill:hover{
        background:#1f2937;
        color:#fff;
    }
    .btn-light-pill{
        background:#fff;
        color:#334155;
        border:1px solid #d6dde8;
    }
    .btn-light-pill:hover{
        background:#f8fafc;
        color:#334155;
    }

    .stat-grid{
        display:grid;
        grid-template-columns:repeat(4,minmax(0,1fr));
        gap:14px;
        margin-bottom:18px;
    }
    .stat-card{
        background:linear-gradient(180deg,#fff,#f8fafc);
        border:1px solid #e5e7eb;
        border-radius:16px;
        padding:16px;
        box-shadow:0 6px 18px rgba(15,23,42,.04);
    }
    .stat-label{
        color:#64748b;
        font-size:13px;
        font-weight:700;
        text-transform:uppercase;
        letter-spacing:.04em;
        margin-bottom:8px;
    }
    .stat-value{
        font-size:28px;
        font-weight:800;
        color:#0f172a;
    }

    .filter-box{
        background:#f8fafc;
        border:1px solid #e2e8f0;
        border-radius:16px;
        padding:16px;
        margin-bottom:18px;
    }
    .filter-row{
        display:grid;
        grid-template-columns:2fr 1fr 1fr 1fr auto;
        gap:12px;
        align-items:end;
    }
    .form-label{
        display:block;
        font-size:14px;
        font-weight:700;
        margin-bottom:8px;
        color:#111827;
    }
    .form-control, .form-select{
        width:100%;
        box-sizing:border-box;
        padding:11px 12px;
        border-radius:12px;
        border:1px solid #d6dde8;
        outline:none;
        background:#fff;
        font-size:14px;
    }
    .form-control:focus, .form-select:focus{
        border-color:#334155;
    }

    .table-wrap{
        overflow-x:hidden;
        border-radius:14px;
    }
    table{
        width:100%;
        border-collapse:collapse;
    }
    thead th{
        background:#1f2937;
        color:#fff;
        text-align:left;
        padding:13px 14px;
        font-size:13px;
        white-space:nowrap;
    }
    tbody td{
        padding:13px 14px;
        border-bottom:1px solid #eef2f7;
        font-size:14px;
        vertical-align:middle;
        white-space:nowrap;
    }
    tbody tr:hover td{
        background:#f8fafc;
    }

    .badge-soft{
        display:inline-flex;
        align-items:center;
        padding:6px 10px;
        border-radius:999px;
        font-size:12px;
        font-weight:700;
        text-transform:capitalize;
    }
    .paid{ background:#dcfce7; color:#166534; }
    .unpaid{ background:#fee2e2; color:#991b1b; }
    .advance{ background:#fef3c7; color:#92400e; }

    .actions{
        display:flex;
        gap:8px;
        flex-wrap:wrap;
        white-space:nowrap;
    }
    .action-btn{
        display:inline-flex;
        align-items:center;
        gap:6px;
        padding:7px 11px;
        border-radius:8px;
        font-size:13px;
        text-decoration:none;
        border:1px solid #d6dde8;
        color:#111827;
        background:#fff;
        white-space:nowrap;
    }
    .action-btn:hover{
        background:#f8fafc;
    }

    .pagination{
        display:flex;
        gap:8px;
        flex-wrap:wrap;
        margin-top:18px;
    }
    .page-link{
        display:inline-flex;
        align-items:center;
        justify-content:center;
        min-width:38px;
        padding:8px 12px;
        border-radius:10px;
        border:1px solid #d6dde8;
        background:#fff;
        text-decoration:none;
        color:#111827;
        font-weight:700;
    }
    .page-link.active{
        background:#334155;
        color:#fff;
        border-color:#334155;
    }
    .empty{
        text-align:center;
        padding:30px 10px;
        color:#64748b;
    }

    @media(max-width: 900px){
        .main-content{
            margin-left:0;
            padding:14px;
        }
        .stat-grid{
            grid-template-columns:repeat(2,minmax(0,1fr));
        }
        .filter-row{
            grid-template-columns:1fr;
        }
        .page-title{
            font-size:24px;
        }
    }
    @media(max-width: 560px){
        .stat-grid{
            grid-template-columns:1fr;
        }
    }
</style>
</head>
<body>

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

<div class="main-content">
    <div class="page-card">

        <div class="header-row">
            <div>
                <h1 class="page-title">
                    <i class="fa-solid fa-receipt"></i>
                    Invoices
                </h1>
                <div class="page-subtitle">View invoice history, payment status, and total billing.</div>
            </div>

            <div class="top-actions">
                <a href="<?php echo build_url(['export' => 'csv']); ?>" class="btn-pill btn-dark-pill">
                    <i class="fa-solid fa-file-csv"></i> Export CSV
                </a>
                <a href="invoices.php" class="btn-pill btn-light-pill">
                    <i class="fa-solid fa-rotate-left"></i> Reset
                </a>
            </div>
        </div>

        <div class="stat-grid">
            <div class="stat-card">
                <div class="stat-label">Total Invoices</div>
                <div class="stat-value"><?php echo (int)$summary['total_invoices']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total Sales</div>
                <div class="stat-value">₹<?php echo money($summary['total_sales']); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Paid</div>
                <div class="stat-value"><?php echo (int)$summary['paid_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Due Amount</div>
                <div class="stat-value">₹<?php echo money($summary['due_sum']); ?></div>
            </div>
        </div>

        <form method="GET" class="filter-box">
            <div class="filter-row">
                <div>
                    <label class="form-label">Search</label>
                    <input type="text" name="q" class="form-control" value="<?php echo e($q); ?>" placeholder="Invoice no, customer, phone, executive">
                </div>

                <div>
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All</option>
                        <option value="paid" <?php echo $status === 'paid' ? 'selected' : ''; ?>>Paid</option>
                        <option value="unpaid" <?php echo $status === 'unpaid' ? 'selected' : ''; ?>>Unpaid</option>
                        <option value="advance" <?php echo $status === 'advance' ? 'selected' : ''; ?>>Advance</option>
                    </select>
                </div>

                <div>
                    <label class="form-label">From</label>
                    <input type="date" name="date_from" class="form-control" value="<?php echo e($date_from); ?>">
                </div>

                <div>
                    <label class="form-label">To</label>
                    <input type="date" name="date_to" class="form-control" value="<?php echo e($date_to); ?>">
                </div>

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

            <div class="mt-3 d-flex gap-2 flex-wrap">
                <a href="<?php echo build_url(['range' => 'today']); ?>" class="btn-pill btn-light-pill">
                    Today
                </a>
                <a href="<?php echo build_url(['range' => 'month']); ?>" class="btn-pill btn-light-pill">
                    This Month
                </a>
                <a href="invoices.php" class="btn-pill btn-light-pill">
                    Clear Range
                </a>
            </div>
        </form>

        <div class="table-wrap">
            <table class="table table-bordered align-middle">
                <thead>
                    <tr>
                        <th>Invoice No</th>
                        <th>Customer</th>
                        <th>Phone</th>
                        <th>Created By</th>
                        <th>Status</th>
                        <th>Subtotal</th>
                        <th>Total</th>
                        <th>Advance</th>
                        <th>Due</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($listRes && $listRes->num_rows > 0): ?>
                    <?php while ($row = $listRes->fetch_assoc()):
                        $st = strtolower($row['payment_status'] ?? 'paid');
                        $cls = in_array($st, ['paid', 'unpaid', 'advance']) ? $st : 'paid';
                    ?>
                        <tr>
                            <td>#<?php echo (int)$row['id']; ?></td>
                            <td><?php echo e($row['customer_name'] ?: '-'); ?></td>
                            <td><?php echo e($row['phone'] ?: '-'); ?></td>
                            <td><?php echo e($row['created_by_name'] ?: '-'); ?></td>
                            <td><span class="badge-soft <?php echo $cls; ?>"><?php echo e($st); ?></span></td>
                            <td>₹<?php echo money($row['subtotal']); ?></td>
                            <td><strong>₹<?php echo money($row['total_amount']); ?></strong></td>
                            <td>₹<?php echo money($row['advance_amount']); ?></td>
                            <td>₹<?php echo money($row['due_amount']); ?></td>
                            <td><?php echo fmt_date($row['created_at']); ?></td>
                            <td>
                                <div class="actions">
                                    <a href="../salesexecutive/view_bill.php?id=<?php echo (int)$row['id']; ?>" class="action-btn">
                                        <i class="fa-solid fa-eye"></i> View
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="11" class="empty">No invoices found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php
                $start = max(1, $page - 2);
                $end   = min($totalPages, $page + 2);

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

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

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

    </div>
</div>

</body>
</html>