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

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

$user_id = (int)($_SESSION['user_id']);
$role    = $_SESSION['role'] ?? 'user';

$canSeeAll    = in_array($role, ['admin', 'agency'], true);
$canManageAll = in_array($role, ['admin', 'agency'], true);

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

if (!function_exists('money')) {
    function money($v) {
        return number_format((float)$v, 2);
    }
}

if (!function_exists('is_valid_date')) {
    function is_valid_date($d) {
        return is_string($d) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $d);
    }
}

$set_due = isset($_GET['set_due']);
$bill_id  = (int)($_GET['bill_id'] ?? 0);
$today    = date('Y-m-d');
$msg      = $_GET['msg'] ?? '';

/* ============================================================
   SAVE DUE DATE
============================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_due'])) {
    $bill_id_post = (int)($_POST['bill_id'] ?? 0);
    $due_date     = trim($_POST['due_date'] ?? '');

    if ($bill_id_post <= 0 || !is_valid_date($due_date)) {
        header("Location: unpaid_sales.php?set_due=1&bill_id=" . $bill_id_post . "&msg=invalid_date");
        exit;
    }

    if ($due_date < $today) {
        header("Location: unpaid_sales.php?set_due=1&bill_id=" . $bill_id_post . "&msg=due_past");
        exit;
    }

    if ($canManageAll) {
        $stmt = $conn->prepare("
            UPDATE bills
            SET unpaid = 1,
                due_date = ?,
                unpaid_due_date = ?,
                payment_status = 'unpaid'
            WHERE id = ?
        ");
        if ($stmt) {
            $stmt->bind_param("ssi", $due_date, $due_date, $bill_id_post);
            $stmt->execute();
            $stmt->close();
        }
    } else {
        $stmt = $conn->prepare("
            UPDATE bills
            SET unpaid = 1,
                due_date = ?,
                unpaid_due_date = ?,
                payment_status = 'unpaid'
            WHERE id = ? AND created_by = ?
        ");
        if ($stmt) {
            $stmt->bind_param("ssii", $due_date, $due_date, $bill_id_post, $user_id);
            $stmt->execute();
            $stmt->close();
        }
    }

    header("Location: unpaid_sales.php?msg=saved");
    exit;
}

/* ============================================================
   MARK AS UNPAID
============================================================ */
if (isset($_GET['type']) && $_GET['type'] === 'unpaid' && !empty($_GET['bill_no'])) {
    $bill_no = (int)$_GET['bill_no'];

    if ($canManageAll) {
        $stmt = $conn->prepare("
            UPDATE bills
            SET unpaid = 1,
                payment_status = 'unpaid'
            WHERE id = ?
        ");
        if ($stmt) {
            $stmt->bind_param("i", $bill_no);
            $stmt->execute();
            $stmt->close();
        }
    } else {
        $stmt = $conn->prepare("
            UPDATE bills
            SET unpaid = 1,
                payment_status = 'unpaid'
            WHERE id = ? AND created_by = ?
        ");
        if ($stmt) {
            $stmt->bind_param("ii", $bill_no, $user_id);
            $stmt->execute();
            $stmt->close();
        }
    }

    header("Location: unpaid_sales.php?msg=unpaid");
    exit;
}

/* ============================================================
   MARK AS PAID (ADMIN ONLY)
============================================================ */
if ($role === 'admin' && isset($_GET['paid_id'])) {
    $id = (int)$_GET['paid_id'];

    $stmt = $conn->prepare("
        UPDATE bills
        SET unpaid = 0,
            unpaid_due_date = NULL,
            payment_status = 'paid'
        WHERE id = ?
    ");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
    }

    header("Location: unpaid_sales.php?msg=paid");
    exit;
}

/* ============================================================
   SET DUE MODE: FETCH BILL
============================================================ */
$bill = null;
if ($set_due && $bill_id > 0) {
    if ($canManageAll) {
        $stmt = $conn->prepare("SELECT * FROM bills WHERE id = ?");
        $stmt->bind_param("i", $bill_id);
    } else {
        $stmt = $conn->prepare("SELECT * FROM bills WHERE id = ? AND created_by = ?");
        $stmt->bind_param("ii", $bill_id, $user_id);
    }

    $stmt->execute();
    $bill = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$bill) {
        die('Bill not found');
    }
}

/* ============================================================
   LIST MODE FILTERS / QUERY
============================================================ */
$where  = "(b.unpaid = 1 OR b.payment_status = 'unpaid' OR b.due_amount > 0)";
$params = [];
$types  = "";

$from = trim($_GET['from'] ?? '');
$to   = trim($_GET['to'] ?? '');

if ($from !== '' && $to !== '' && is_valid_date($from) && is_valid_date($to)) {
    if ($from > $to) {
        $tmp  = $from;
        $from = $to;
        $to   = $tmp;
    }
    $where .= " AND DATE(b.created_at) BETWEEN ? AND ?";
    $params[] = $from;
    $params[] = $to;
    $types   .= "ss";
}

if ($role === 'admin') {
    // admin sees all
}
elseif ($role === 'agency') {

    // agency → managers + their MR
    $where .= " AND b.created_by IN (

        -- managers under this agency
        SELECT id FROM users WHERE agency_id = ?

        UNION

        -- MR under those managers
        SELECT id FROM users 
        WHERE manager_id IN (
            SELECT id FROM users WHERE agency_id = ?
        )

    )";

    $params[] = $user_id;
    $params[] = $user_id;
    $types .= "ii";
}
elseif ($role === 'sales_manager') {

    // manager → own + own MR
    $where .= " AND b.created_by IN (
        SELECT id FROM users WHERE manager_id = ?
        UNION
        SELECT ?
    )";

    $params[] = $user_id;
    $params[] = $user_id;
    $types .= "ii";
}
else {

    // MR → only own
    $where .= " AND b.created_by = ?";
    $params[] = $user_id;
    $types .= "i";
}
$sql = "
    SELECT
        b.*,
        COALESCE(u.name, 'System') AS creator_name,
        COALESCE(u.role, '—') AS creator_role,
        COALESCE((
            SELECT COUNT(*)
            FROM bill_items bi
            WHERE bi.bill_id = b.id
        ), 0) AS items_count
    FROM bills b
    LEFT JOIN users u ON u.id = b.created_by
    WHERE $where
    ORDER BY b.id DESC
";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    die('Query prepare failed: ' . $conn->error);
}

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

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

$bills = [];
$totalBills = 0;
$totalPending = 0;
$totalPaid = 0;
$totalAmount = 0;

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $row['items_count'] = (int)($row['items_count'] ?? 0);
        $row['created_at_fmt'] = !empty($row['created_at']) ? date('d-m-Y', strtotime($row['created_at'])) : '—';
        $row['bill_no'] = 'BILL-' . (int)$row['id'];
        $row['creator_name'] = trim((string)($row['creator_name'] ?? '')) ?: 'System';
        $row['creator_role'] = trim((string)($row['creator_role'] ?? '')) ?: '—';
        $row['total_amount_num'] = (float)($row['total_amount'] ?? 0);
        $row['advance_amount_num'] = (float)($row['advance_amount'] ?? 0);
        $row['due_amount_num'] = (float)($row['due_amount'] ?? 0);

        $totalBills++;
        $totalAmount += $row['total_amount_num'];
        $totalPaid += $row['advance_amount_num'];
        $totalPending += $row['due_amount_num'];

        $bills[] = $row;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Unpaid Bills</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>

<style>
:root{
    --bg:#eef3f9;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#64748b;
    --theme:#334155;
    --theme-dark:#1f2937;
    --stroke:#e5eaf2;
    --soft:#f7fbff;
    --success:#16a34a;
    --danger:#dc2626;
    --warning:#f59e0b;
    --shadow:0 12px 30px rgba(15,23,42,.08);
    --shadow-soft:0 8px 20px rgba(15,23,42,.06);
    --radius:20px;
}

*{
    box-sizing:border-box;
}

html,body{
    margin:0;
    padding:0;
    background:var(--bg);
    color:var(--text);
    font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;
    overflow-x:hidden;
}

body{
    font-size:14px;
    line-height:1.5;
}

.container{
    margin-left:260px;
    padding:100px 24px 24px;
    width:calc(100% - 260px);
}

/* ===== PAGE HEADER ===== */
.page-head{
    display:flex;
    justify-content:space-between;
    align-items:flex-end;
    gap:16px;
    flex-wrap:wrap;
    margin-bottom:18px;
}

.page-title{
    margin:0;
    font-size:30px;
    font-weight:900;
    letter-spacing:-0.03em;
    color:#000;
}

.page-subtitle{
    margin:6px 0 0;
    color:#64748b;
    font-size:14px;
    font-weight:500;
}

/* ===== CARDS ===== */
.card{
    background:var(--card);
    border:1px solid #edf2f7;
    border-radius:var(--radius);
    box-shadow:var(--shadow);
}

.hero-card{
    padding:20px;
    margin-bottom:18px;
    background:linear-gradient(135deg,#f8fafc,#eef3f9);
    border:1px solid #e2e8f0;
    border-radius:20px;
    box-shadow:0 10px 30px rgba(0,0,0,0.06);
}

.toolbar{
    display:flex;
    justify-content:space-between;
    align-items:flex-end;
    gap:14px;
    flex-wrap:wrap;
}

.filter-row{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    align-items:end;
    width:100%;
}

.field{
    display:flex;
    flex-direction:column;
    gap:8px;
    flex:1 1 220px;
    min-width:220px;
}

.field label,
.control label{
    font-weight:800;
    color:#1e293b;
    font-size:13px;
}

/* ===== INPUTS ===== */
.input{
    width:100%;
    height:50px;
    padding:0 14px;
    border-radius:14px;
    border:1px solid #e2e8f0;
    background:#f8fafc;
    outline:none;
    color:var(--text);
    transition:all 0.25s ease;
    font-size:14px;
}

.input:focus{
    border-color:#334155;
    box-shadow:0 0 0 4px rgba(51,65,85,0.10);
}

.search-box{
    flex:1;
    min-width:300px;
    height:54px;
    border-radius:16px;
    padding:0 18px;
    font-size:15px;
}

/* ===== BUTTONS ===== */
.btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    border:none;
    border-radius:14px;
    padding:0 16px;
    height:50px;
    background:linear-gradient(135deg,#334155,#1e293b);
    box-shadow:0 6px 18px rgba(51,65,85,0.25);
    color:#fff;
    font-weight:800;
    cursor:pointer;
    text-decoration:none;
    transition:.2s ease;
    white-space:nowrap;
}

.btn:hover{
    transform:translateY(-2px);
    box-shadow:0 10px 22px rgba(51,65,85,0.30);
}

.btn.secondary{
    background:#f1f5f9;
    color:var(--theme-dark);
    box-shadow:none;
}

.btn.success{
    background:var(--success);
}

.btn.danger{
    background:var(--danger);
}

.btn.warning{
    background:var(--warning);
    color:#fff;
}

/* ===== PILLS ===== */
.pill{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:10px 14px;
    border-radius:999px;
    background:var(--soft);
    color:var(--theme);
    font-weight:800;
    border:1px solid #dbe7f5;
    white-space:nowrap;
}

.pill.dark{
    background:#334155;
    color:#fff;
    border:none;
}

/* ===== SUMMARY ===== */
.summary{
    display:grid;
    grid-template-columns:repeat(4,minmax(0,1fr));
    gap:14px;
    margin-top:16px;
}

.stat{
    border-radius:18px;
    padding:18px;
    background:linear-gradient(135deg,#ffffff,#f8fafc);
    border:1px solid #e2e8f0;
    transition:all 0.25s ease;
    position:relative;
    overflow:hidden;
}

.stat:hover{
    transform:translateY(-4px);
    box-shadow:0 12px 25px rgba(0,0,0,0.08);
}

.stat .label{
    color:#64748b;
    font-weight:800;
    font-size:11px;
    text-transform:uppercase;
    letter-spacing:.12em;
}

.stat .value{
    font-size:26px;
    font-weight:900;
    margin-top:6px;
}

.stat:nth-child(1) .value{
    color:#16a34a;
}

.stat:nth-child(2) .value{
    color:#2563eb;
}

.stat:nth-child(3) .value{
    color:#16a34a;
}

.stat:nth-child(4) .value{
    color:#dc2626;
}

/* ===== TABLE ===== */
.table-card{
    background:var(--card);
    border:1px solid #edf2f7;
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    overflow:hidden;
}

.table-wrap{
    width:100%;
    overflow-x:auto;   /* important */
}

.grid-head,
.grid-row{
    min-width:1100px;
}

.grid-head{
    display:grid;
    grid-template-columns:repeat(12,1fr);
    align-items:center;
    padding:14px 16px;
    background:linear-gradient(135deg,#334155,#1e293b);
    color:#fff;
    font-weight:900;
    border-radius:16px 16px 0 0;
}

.grid-head > div{
    font-weight:800;
    font-size:14px;
    color:#fff;
}

.grid-row{
    display:grid;
    grid-template-columns:repeat(12,1fr);
    width:100%;
    padding:12px 16px;
    border-bottom:1px solid #eef2f7;
    align-items:center;
    transition:0.2s ease;
}

.grid-row:last-child{
    border-bottom:none;
    margin-bottom:0;
}

.grid-row:hover{
    background:#f8fafc;
}

.grid-row > div{
    display:flex;
    align-items:center;
    justify-content:flex-start;
    min-width:0;
    padding:4px 6px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

.grid-row > div:nth-child(1),
.grid-row > div:nth-child(2),
.grid-row > div:nth-child(3),
.grid-row > div:nth-child(4),
.grid-row > div:nth-child(11),
.grid-row > div:nth-child(12){
    justify-content:center;
}

.grid-row > div:nth-child(7),
.grid-row > div:nth-child(8),
.grid-row > div:nth-child(9){
    justify-content:flex-end;
}

.grid-row > div:nth-child(5),
.grid-row > div:nth-child(6),
.grid-row > div:nth-child(10){
    justify-content:flex-start;
}

.cell{
    word-break:break-word;
}

.value{
    color:#0f172a;
    font-weight:600;
}

.badge{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:6px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:800;
    border:1px solid transparent;
    white-space:nowrap;
}

.badge.bill{
    background:#eef2ff;
    color:#3730a3;
    border-color:#c7d2fe;
}

.badge.creator{
    background:#ecfeff;
    color:#155e75;
    border-color:#a5f3fc;
}

.badge.role-manager{
    background:#fef3c7;
    color:#92400e;
    border-color:#fcd34d;
}

.badge.role-medical-representative{
    background:#dcfce7;
    color:#166534;
    border-color:#86efac;
}

.badge.role-agency{
    background:#dbeafe;
    color:#1d4ed8;
    border-color:#93c5fd;
}

.badge.role-admin{
    background:#f3e8ff;
    color:#7e22ce;
    border-color:#d8b4fe;
}

.badge.role-default{
    background:#f1f5f9;
    color:#334155;
    border-color:#cbd5e1;
}

.badge.status-unpaid{
    background:#fff7ed;
    color:#9a3412;
    border-color:#fed7aa;
}

.badge.status-paid{
    background:#ecfdf5;
    color:#166534;
    border-color:#a7f3d0;
}

.amount-green{
    color:#16a34a;
    font-weight:800;
}

.amount-red{
    color:#dc2626;
    font-weight:800;
}

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

.actions{
    display:flex;
    align-items:center;
    justify-content:flex-start;
    gap:8px;
    flex-wrap:wrap;
}

.action-btn{
    width:42px;
    height:42px;
    display:flex;
    align-items:center;
    justify-content:center;
    border-radius:12px;
    background:#f8fafc;
    border:1px solid #e2e8f0;
    color:#334155;
    text-decoration:none;
    transition:all 0.2s ease;
}

.action-btn:hover{
    background:#e2e8f0;
    transform:translateY(-1px);
}

.action-btn.invoice{
    background:#eef2ff;
    color:#3730a3;
    border-color:#c7d2fe;
}

.action-btn.paid{
    background:var(--success);
    color:#fff;
    border-color:var(--success);
}

.small-form{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    align-items:center;
}

.empty{
    margin:16px;
    padding:22px;
    text-align:center;
    color:var(--muted);
    background:#fafcff;
    border:1px dashed #dbe3ec;
    border-radius:14px;
    font-weight:700;
}

/* ===== TOAST ===== */
.toast{
    position:fixed;
    right:20px;
    bottom:20px;
    background:#111827;
    color:#fff;
    padding:12px 16px;
    border-radius:12px;
    font-weight:700;
    display:none;
    z-index:9999;
    box-shadow:0 12px 30px rgba(0,0,0,.18);
}

/* ===== FORM VIEW ===== */
.form-shell{
    max-width:1100px;
    margin:0 auto;
}

.form-card{
    padding:22px;
}

.form-header{
    display:flex;
    justify-content:space-between;
    gap:16px;
    align-items:flex-start;
    flex-wrap:wrap;
    margin-bottom:18px;
}

.form-title{
    margin:0;
    font-size:26px;
    font-weight:900;
    color:var(--theme-dark);
}

.form-desc{
    margin:6px 0 0;
    color:var(--muted);
    font-size:14px;
}

.bill-meta{
    display:grid;
    grid-template-columns:repeat(3,minmax(0,1fr));
    gap:12px;
    margin-bottom:18px;
}

.meta-box{
    border:1px solid #e8eef6;
    background:#fbfdff;
    border-radius:16px;
    padding:14px;
}

.meta-label{
    display:block;
    font-size:12px;
    text-transform:uppercase;
    letter-spacing:.08em;
    color:var(--muted);
    font-weight:800;
    margin-bottom:8px;
}

.meta-value{
    font-size:16px;
    font-weight:800;
    color:var(--theme-dark);
    word-break:break-word;
}

.due-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:16px;
    margin-top:8px;
}

.control{
    display:flex;
    flex-direction:column;
    gap:8px;
}

.actions-row{
    margin-top:20px;
    display:flex;
    gap:10px;
    justify-content:flex-end;
    flex-wrap:wrap;
}

/* ===== TITLE / PILL ===== */
.page-title span{
    background:linear-gradient(135deg,#2563eb,#3b82f6);
    color:#fff;
    padding:4px 10px;
    border-radius:8px;
    font-size:22px;
    font-weight:800;
}

.pill{
    background:linear-gradient(135deg,#f1f5f9,#e2e8f0);
    border:1px solid #e2e8f0;
    color:#1e293b;
    font-weight:800;
    padding:10px 16px;
    border-radius:999px;
    box-shadow:0 4px 10px rgba(0,0,0,0.05);
}

/* ===== RESPONSIVE ===== */
@media (max-width:1180px){
    .summary{
        grid-template-columns:repeat(2,minmax(0,1fr));
    }
}

@media (max-width:1100px){
    .grid-head{
        display:none;
    }

    .grid-row{
        display:block;
        min-width:0;
        margin:12px 12px 0;
        background:#fff;
        border:1px solid #edf2f7;
        border-radius:16px;
        padding:12px;
        box-shadow:0 8px 20px rgba(15,23,42,.06);
    }

    .grid-row > div{
        display:flex;
        justify-content:space-between;
        gap:14px;
        padding:9px 0;
        border-bottom:1px dashed #eef2f7;
        white-space:normal;
    }

    .grid-row > div:last-child{
        border-bottom:none;
    }

    .grid-row > div::before{
        content:attr(data-label);
        font-weight:800;
        color:var(--muted);
        flex:0 0 42%;
        max-width:42%;
    }

    .grid-row > div > .value{
        flex:1;
        text-align:right;
    }

    .grid-row > div > .actions{
        justify-content:flex-end;
    }

    .bill-meta{
        grid-template-columns:1fr;
    }
}

@media (max-width:768px){
    .container{
        margin-left:0;
        width:100%;
        padding:90px 12px 12px;
    }

    .page-title{
        font-size:22px;
    }

    .input,
    .input[type="search"]{
        width:100%;
        min-width:0;
    }

    .field{
        min-width:0;
        flex:1 1 100%;
    }

    .btn{
        width:100%;
    }

    .actions-row{
        justify-content:stretch;
    }

    .actions-row .btn,
    .actions-row a{
        width:100%;
    }

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

    .due-grid{
        grid-template-columns:1fr;
    }
}
</style>
</head>
<body>

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

<div class="container">

<?php if ($msg === 'saved'): ?>
    <div class="toast" id="toast" style="display:block;">Saved successfully</div>
<?php elseif ($msg === 'paid'): ?>
    <div class="toast" id="toast" style="display:block;">Marked paid</div>
<?php elseif ($msg === 'unpaid'): ?>
    <div class="toast" id="toast" style="display:block;">Marked unpaid</div>
<?php elseif ($msg === 'due_past'): ?>
    <div class="toast" id="toast" style="display:block;">Due date cannot be earlier than today</div>
<?php elseif ($msg === 'invalid_date'): ?>
    <div class="toast" id="toast" style="display:block;">Invalid date provided</div>
<?php else: ?>
    <div class="toast" id="toast"></div>
<?php endif; ?>

<?php if ($set_due && $bill): ?>

    <?php
        $from_date = !empty($bill['created_at']) ? date('Y-m-d', strtotime($bill['created_at'])) : $today;
        $due_date  = !empty($bill['unpaid_due_date']) ? date('Y-m-d', strtotime($bill['unpaid_due_date'])) : $today;
        $bill_no   = 'BILL-' . (int)$bill['id'];
        $cust_name = trim((string)($bill['customer_name'] ?? '')) ?: '—';
        $phone     = trim((string)($bill['phone'] ?? '')) ?: '—';
        $total_amt = isset($bill['total_amount']) ? money($bill['total_amount']) : '0.00';
        $creator   = trim((string)($bill['creator_name'] ?? '')) ?: 'System';
        $creatorRole = trim((string)($bill['creator_role'] ?? '')) ?: '—';
    ?>

    <div class="form-shell">
        <div class="page-head">
            <div>
                <h1 class="page-title">Unpaid Bills</h1>
                <p class="page-subtitle">Set the unpaid start date and payment due date for this bill.</p>
            </div>
            <div class="pill">
                <i class="fa-solid fa-receipt"></i> Bill #<?php echo (int)$bill['id']; ?>
            </div>
        </div>

        <div class="card form-card">
            <div class="form-header">
                <div>
                    <h2 class="form-title">Unpaid Finalize</h2>
                    <p class="form-desc">Please confirm the unpaid period and due date.</p>
                </div>
            </div>

            <div class="bill-meta">
                <div class="meta-box">
                    <span class="meta-label">Bill No.</span>
                    <div class="meta-value"><?php echo e($bill_no); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Customer</span>
                    <div class="meta-value"><?php echo e($cust_name); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Phone</span>
                    <div class="meta-value"><?php echo e($phone); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Total Amount</span>
                    <div class="meta-value">₹ <?php echo e($total_amt); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Created By</span>
                    <div class="meta-value"><?php echo e($creator); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Role</span>
                    <div class="meta-value"><?php echo e($creatorRole); ?></div>
                </div>
            </div>

            <form method="POST">
                <input type="hidden" name="bill_id" value="<?php echo (int)$bill_id; ?>">

                <div class="due-grid">
                    <div class="control">
                        <label>Unpaid From</label>
                        <input type="date" class="input" value="<?php echo e($from_date); ?>" readonly>
                    </div>

                    <div class="control">
                        <label>Payment Due Date</label>
                        <input type="date" name="due_date" class="input" min="<?php echo e($today); ?>" value="<?php echo e($due_date); ?>" required>
                    </div>
                </div>

                <div class="actions-row">
                    <a href="unpaid_sales.php" class="btn secondary">
                        <i class="fa-solid fa-xmark"></i> Cancel
                    </a>
                    <button type="submit" name="save_due" class="btn">
                        <i class="fa-solid fa-floppy-disk"></i> Save
                    </button>
                </div>
            </form>
        </div>
    </div>

<?php else: ?>

    <div class="page-head">
        <div>
            <h1 class="page-title">Unpaid Bills</h1>
            <p class="page-subtitle">Agency view: see all unpaid bills, who created them, and how much is still pending.</p>
        </div>
        <div class="pill">
            <i class="fa-solid fa-receipt"></i> <?php echo (int)$totalBills; ?> Bills
        </div>
    </div>

    <div class="hero-card card">
        <form method="GET" class="toolbar">
            <div class="filter-row">
                <div class="field">
                    <label>From</label>
                    <input type="date" name="from" class="input" value="<?php echo e($_GET['from'] ?? ''); ?>">
                </div>

                <div class="field">
                    <label>To</label>
                    <input type="date" name="to" class="input" value="<?php echo e($_GET['to'] ?? ''); ?>">
                </div>

                <div style="display:flex; gap:10px; align-items:flex-end; flex-wrap:wrap;">
                    <button type="button" class="btn secondary" onclick="setToday()">
                        Today
                    </button>
                    <button type="button" class="btn secondary" onclick="setThisMonth()">
                        This Month
                    </button>
                    <button class="btn" type="submit">
                        <i class="fa-solid fa-magnifying-glass"></i> Search
                    </button>
                </div>
            </div>
        </form>

        <div class="summary">
            <div class="stat">
                <div class="label">Bills</div>
                <div class="value" id="countTop"><?php echo (int)$totalBills; ?></div>
            </div>
            <div class="stat">
                <div class="label">Total Amount</div>
                <div class="value">₹<?php echo e(money($totalAmount)); ?></div>
            </div>
            <div class="stat">
                <div class="label">Paid Amount</div>
                <div class="value">₹<?php echo e(money($totalPaid)); ?></div>
            </div>
            <div class="stat">
                <div class="label">Pending Amount</div>
                <div class="value">₹<?php echo e(money($totalPending)); ?></div>
            </div>
        </div>
    </div>

    <div class="hero-card card" style="padding:14px 18px;">
        <div class="toolbar">
            <input type="search" id="search" class="input search-box" placeholder="Search Bill No, Customer, Creator, Role, Phone">

            <div style="display:flex; gap:12px; align-items:center; flex-wrap:wrap;">
                <div class="pill dark">All Time</div>
                <div class="pill dark" id="count"><?php echo (int)$totalBills; ?> bills</div>
                <button type="button" id="excelBtn" class="btn secondary" style="height:54px;border-radius:999px;padding:0 18px;">
                    <i class="fa-solid fa-file-excel"></i> Export CSV
                </button>
            </div>
        </div>
    </div>

    <div class="table-card">
        <div class="table-wrap">
            <div class="grid-head">
                <div>Date</div>
                <div>Bill</div>
                <div>Creator</div>
                <div>Role</div>
                <div>Customer</div>
                <div>Phone</div>
                <div>Total</div>
                <div>Paid</div>
                <div>Pending</div>
                <div>Due Date</div>
                <div>Status</div>
                <div>Action</div>
            </div>

            <div id="list">
                <?php if (!empty($bills)): ?>
                    <?php foreach ($bills as $r): ?>
                        <?php
                            $billId  = (int)$r['id'];
                            $created = $r['created_at_fmt'];
                            $billNo  = $r['bill_no'];
                            $phone   = trim((string)($r['phone'] ?? '')) ?: '—';
                            $cust    = trim((string)($r['customer_name'] ?? '')) ?: '—';
                            $items   = (int)($r['items_count'] ?? 0);
                            $total   = money($r['total_amount_num']);
                            $paid    = money($r['advance_amount_num']);
                            $pending = money($r['due_amount_num']);
                            $dueRaw  = !empty($r['unpaid_due_date']) ? $r['unpaid_due_date'] : ($r['due_date'] ?? '');
                            $dueDate = !empty($dueRaw) ? date('d-m-Y', strtotime($dueRaw)) : '—';
                            $creator = $r['creator_name'] ?: 'System';
                            $creatorRole = strtolower(trim((string)$r['creator_role']));
                            $status = (!empty($r['payment_status']) && $r['payment_status'] === 'paid') ? 'paid' : 'unpaid';

                            $roleClass = 'role-default';
                            if ($creatorRole === 'manager' || $creatorRole === 'sales_manager') {
                                $roleClass = 'role-manager';
                            } elseif ($creatorRole === 'medical representative' || $creatorRole === 'medical_representative' || $creatorRole === 'medical_rep' || $creatorRole === 'sales_executive') {
                                $roleClass = 'role-medical-representative';
                            } elseif ($creatorRole === 'agency') {
                                $roleClass = 'role-agency';
                            } elseif ($creatorRole === 'admin') {
                                $roleClass = 'role-admin';
                            }
                        ?>
                        <div class="grid-row data">
                            <div data-label="Date"><span class="value"><?php echo e($created); ?></span></div>

                            <div data-label="Bill">
                                <span class="value badge bill"><?php echo e($billNo); ?></span>
                            </div>

                            <div data-label="Creator">
                                <span class="value badge creator"><?php echo e($creator); ?></span>
                            </div>

                            <div data-label="Role">
                                <span class="value badge <?php echo e($roleClass); ?>"><?php echo e($creatorRole ?: '—'); ?></span>
                            </div>

                            <div data-label="Customer"><span class="value"><?php echo e($cust); ?></span></div>
                            <div data-label="Phone"><span class="value"><?php echo e($phone); ?></span></div>

                            <div data-label="Total">
                                <span class="value amount-dark">₹<?php echo e($total); ?></span>
                            </div>

                            <div data-label="Paid">
                                <span class="value amount-green">₹<?php echo e($paid); ?></span>
                            </div>

                            <div data-label="Pending">
                                <span class="value amount-red">₹<?php echo e($pending); ?></span>
                            </div>

                            <div data-label="Due Date">
                                <span class="value"><?php echo e($dueDate); ?></span>
                            </div>

                            <div data-label="Status">
                                <span class="value badge <?php echo $status === 'paid' ? 'status-paid' : 'status-unpaid'; ?>">
                                    <?php echo e($status); ?>
                                </span>
                            </div>

                            <div data-label="Action">
                                <span class="value actions">
                                    <a href="invoice_view.php?id=<?php echo $billId; ?>" class="action-btn invoice" title="Invoice">
                                        <i class="fa-regular fa-file-lines"></i>
                                    </a>

                                    <?php if ($role === 'admin'): ?>
                                        <a href="?paid_id=<?php echo $billId; ?>" class="action-btn paid" title="Mark Paid" onclick="return confirm('Mark this bill as paid?');">
                                            <i class="fa-solid fa-check"></i>
                                        </a>
                                    <?php endif; ?>
                                </span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty">No unpaid bills found</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

<?php endif; ?>

</div>

<script>
function setToday() {
    const today = new Date().toISOString().split('T')[0];
    const from = document.querySelector("input[name='from']");
    const to = document.querySelector("input[name='to']");
    if (from) from.value = today;
    if (to) to.value = today;
}

function setThisMonth() {
    const now = new Date();
    const first = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0];
    const last  = new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString().split('T')[0];
    const from = document.querySelector("input[name='from']");
    const to = document.querySelector("input[name='to']");
    if (from) from.value = first;
    if (to) to.value = last;
}

document.addEventListener('DOMContentLoaded', function () {
    const input = document.getElementById('search');
    const rows  = Array.from(document.querySelectorAll('.grid-row.data'));
    const count = document.getElementById('count');
    const countTop = document.getElementById('countTop');
    const toast = document.getElementById('toast');

    function update() {
        const q = (input?.value || '').toLowerCase().trim();
        let visible = 0;

        rows.forEach(row => {
            const text = row.innerText.toLowerCase();
            const show = text.includes(q);
            row.style.display = show ? '' : 'none';
            if (show) visible++;
        });

        if (count) count.textContent = visible + (visible === 1 ? ' bill' : ' bills');
        if (countTop) countTop.textContent = visible;
    }

    if (input && rows.length) {
        input.addEventListener('input', update);
        update();
    }

    const msg = <?php echo json_encode($msg); ?>;
    const map = {
        paid: 'Marked paid',
        saved: 'Saved successfully',
        due_past: 'Due date cannot be earlier than today',
        invalid_date: 'Invalid date provided',
        unpaid: 'Marked unpaid'
    };

    if (toast && msg && map[msg]) {
        toast.textContent = map[msg];
        toast.style.display = 'block';
        setTimeout(() => {
            toast.style.display = 'none';
        }, 3000);
    }

    document.getElementById('excelBtn')?.addEventListener('click', function () {
        downloadCSV();
    });
});

function downloadCSV() {
    const rows = Array.from(document.querySelectorAll('.grid-row.data'))
        .filter(row => row.style.display !== 'none');

    const headers = [
        "Date",
        "Bill",
        "Creator",
        "Role",
        "Customer",
        "Phone",
        "Items",
        "Total",
        "Paid",
        "Pending",
        "Due Date",
        "Status"
    ];

    let csv = headers.join(",") + "\n";

    rows.forEach(row => {
        const cells = row.querySelectorAll(':scope > div');

        const rowData = [
            cells[0]?.innerText.trim() || '',
            cells[1]?.innerText.trim() || '',
            cells[2]?.innerText.trim() || '',
            cells[3]?.innerText.trim() || '',
            cells[4]?.innerText.trim() || '',
            cells[5]?.innerText.trim() || '',
            cells[6]?.innerText.trim() || '',
            cells[7]?.innerText.replace(/₹|,/g,'').trim() || '',
            cells[8]?.innerText.replace(/₹|,/g,'').trim() || '',
            cells[9]?.innerText.replace(/₹|,/g,'').trim() || '',
            cells[10]?.innerText.trim() || '',
            cells[11]?.innerText.trim() || ''
        ];

        csv += rowData.map(v => `"${String(v).replace(/"/g, '""')}"`).join(",") + "\n";
    });

    const blob = new Blob(["\ufeff" + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = 'unpaid_bills.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);

    URL.revokeObjectURL(url);
}
</script>

</body>
</html>