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



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

if ($role === 'medical_representative') {

    $stmt = $conn->prepare("
        SELECT b.*,
               b.due_amount AS unpaid,
               COALESCE(b.unpaid_due_date, b.due_date) AS final_due_date
        FROM bills b
        WHERE b.mr_id = ?
          AND b.due_amount > 0
          AND b.payment_status != 'paid'
          AND b.due_amount > 0
        ORDER BY final_due_date ASC
    ");
    $stmt->bind_param("i", $user_id);

} elseif ($role === 'sales_manager') {

    $stmt = $conn->prepare("
        SELECT b.*,
               b.due_amount AS unpaid,
               COALESCE(b.unpaid_due_date, b.due_date) AS final_due_date
        FROM bills b
        JOIN users u ON u.id = b.mr_id
        WHERE u.manager_id = ?
          AND b.due_amount > 0
          AND b.payment_status != 'paid'
          AND b.due_amount > 0
        ORDER BY final_due_date ASC
    ");
    $stmt->bind_param("i", $user_id);

} else {

    $stmt = $conn->prepare("
        SELECT b.*,
               b.due_amount AS unpaid,
               COALESCE(b.unpaid_due_date, b.due_date) AS final_due_date
        FROM bills b
        WHERE b.due_amount > 0
          AND b.payment_status != 'paid'
          AND b.due_amount > 0
        ORDER BY final_due_date ASC
    ");
}
$stmt->execute();
$result = $stmt->get_result();
$alertCount = $result->num_rows;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Due Alert</title>

    <style>
        :root{
            --bg:#f4f7fb;
            --card:#ffffff;
            --head:#334155;
            --text:#0f172a;
            --muted:#64748b;
            --border:#e7ebf2;
            --primary:#334155;
            --primary-dark:#1f2937;
            --danger:#dc2626;
            --success:#16a34a;
            --shadow:0 10px 28px rgba(15,23,42,.06);
            --radius:18px;
            --sidebar-width:260px;
        }

        *{ 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;
        }

 .main-content{
    margin-left:var(--sidebar-width);
    margin-left:260px;
    padding:20px 20px 20px;
    position:relative;
    top:-35px;
}

header{
    margin-bottom:0 !important;
}
        .page-card{
             margin-top:0;
            background:var(--card);
            border-radius:14px;
            box-shadow:var(--shadow);
            padding:16px;
            border:1px solid #edf2f7;
        }

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

        .title-wrap{
            display:flex;
            align-items:center;
            gap:14px;
        }

        .title-icon{
            width:40px;
            height:40px;
            border-radius:10px;
            background:var(--primary);
            color:#fff;
            display:flex;
            align-items:center;
            justify-content:center;
            font-size:16px;
            flex:0 0 auto;
            box-shadow:0 8px 18px rgba(51,65,85,.15);
        }

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

        .page-title{
            margin:0;
            font-size:22px;
            font-weight:700;
            color:#000;
            line-height:1.1;
        }

        .page-subtitle{
            margin:0;
            font-size:13px;
            color:var(--muted);
        }

        .alert-badge{
            background:var(--primary);
            color:#fff;
            padding:6px 12px;
            border-radius:999px;
            font-size:12px;
            font-weight:800;
            white-space:nowrap;
            box-shadow:0 6px 14px rgba(32,50,74,.15);
        }

        .top-bar{
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:12px;
            flex-wrap:wrap;
            margin-bottom:14px;
        }

        .search-wrap{
            display:flex;
            align-items:center;
            gap:10px;
            background:#fff;
            border:1px solid #d8e0ea;
            border-radius:14px;
            padding:12px 14px;
            min-width:320px;
            max-width:460px;
            width:100%;
            box-shadow:0 1px 2px rgba(0,0,0,.03);
        }

        .search-wrap i{
            font-style:normal;
            font-size:18px;
            color:#111827;
            flex:0 0 auto;
        }

        .search-wrap input{
            border:none;
            outline:none;
            width:100%;
            font-size:13px;
            background:transparent;
            color:var(--text);
        }

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

        .grid-head,
        .grid-row{
            display:grid;
            grid-template-columns: 110px minmax(180px, 1.4fr) 130px 140px 140px 110px;
            align-items:center;
            min-width:900px;
        }

        .grid-head{
            background:var(--head);
            color:#fff;
            font-weight:800;
            text-transform:uppercase;
            letter-spacing:.3px;
            font-size:13px;
            border-radius:14px;
            overflow:hidden;
        }

        .grid-head > div{
            padding:10px;
            display:flex;
            align-items:center;
            min-height:48px;
        }

        .grid-row{
            margin-top:8px;
            background:#fff;
            border:1px solid var(--border);
            border-radius:14px;
            box-shadow:0 1px 3px rgba(15,23,42,.03);
            transition:.18s ease;
        }

        .grid-row:hover{
            background:#fbfcfe;
            transform:translateY(-1px);
        }

        .grid-row > div{
            padding:10px;
            font-size:13px;
            display:flex;
            align-items:center;
            min-height:66px;
        }

        .bill-no{
            font-weight:800;
            color:#111827;
        }

        .customer{
            font-weight:700;
             font-size:13px;
            color:#111827;
        }

        .unpaid{
            color:var(--danger);
            font-weight:800;
             font-size:13px;
        }

        .date{
            font-weight:600;
            color:#111827;
        }

        .days-left{
            font-weight:700;
            color:#334155;
        }

        .expired{
            display:inline-block;
            background:#fff1f2;
            color:#be123c;
            padding:4px 8px;
            border-radius:999px;
            font-size:11px;
            font-weight:800;
        }

        .view-btn{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            background:var(--primary);
            color:#fff;
            text-decoration:none;
            padding:6px 10px;
            border-radius:8px;
            font-size:12px;
            font-weight:800;
            transition:.2s ease;
            min-width:74px;
        }

        .view-btn:hover{
            transform:translateY(-1px);
            background:var(--primary-dark);
        }

        .no-data{
            text-align:center;
            padding:20px;
            color:var(--success);
            font-weight:800;
            font-size:14px;
            background:#fff;
            border:1px dashed #cbd5e1;
            border-radius:14px;
            margin-top:12px;
        }

        @media (max-width: 880px){
            .main-content{
                margin-left:0;
                padding:14px;
            }

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

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

            .page-card{
                padding:14px;
            }
        }
    </style>
</head>
<body>

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

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

        <div class="page-header">
            <div class="title-wrap">
                <div class="title-icon">
                    <i class="fa-solid fa-triangle-exclamation"></i>
                </div>
                <div class="title-block">
                    <h1 class="page-title" style="color: #000;">Due Alert</h1>
                    <p class="page-subtitle">Overdue bills and pending payments</p>
                </div>
            </div>

            <div class="alert-badge">
                <?= (int)$alertCount ?> alerts
            </div>
        </div>

        <div class="top-bar">
            <div class="search-wrap">
                <i>⌕</i>
                <input type="text" id="quickSearch" placeholder="Quick filter (bill / customer / date)">
            </div>
        </div>

        <div class="table-wrap">
            <div class="grid-head">
                <div>Bill</div>
                <div>Customer</div>
                <div>Unpaid</div>
                <div>Due Date</div>
                <div>Days Left</div>
                <div>Action</div>
            </div>

            <div id="rowsContainer">
                <?php if ($alertCount > 0): ?>
                    <?php while ($row = $result->fetch_assoc()): 
                        $dueText = 'Not Set';
                        $daysText = 'Not Set';
                        $searchText = strtolower(
                            ($row['id'] ?? '') . ' ' .
                            ($row['customer_name'] ?? '') . ' ' .
                            ($row['final_due_date'] ?? '') . ' ' .
                            ($row['due_amount'] ?? '')
                        );

                        if (!empty($row['final_due_date']) && $row['final_due_date'] !== '0000-00-00') {
                            $today = new DateTime(date('Y-m-d'));
                            $dueDate = new DateTime($row['final_due_date']);
                            $diffDays = (int)$today->diff($dueDate)->format('%r%a');

                            $dueText = $dueDate->format('d M Y');

                            if ($diffDays < 0) {
                                $daysText = 'Expired ' . abs($diffDays) . 'd ago';
                            } elseif ($diffDays === 0) {
                                $daysText = 'Today';
                            } else {
                                $daysText = $diffDays . 'd left';
                            }
                        }
                    ?>
                        <div class="grid-row data" data-search="<?= htmlspecialchars($searchText) ?>">
                            <div data-label="Bill"><span class="bill-no"><?= (int)$row['id'] ?></span></div>

                            <div data-label="Customer"><span class="customer"><?= htmlspecialchars($row['customer_name'] ?? 'N/A') ?></span></div>

                            <div data-label="Unpaid"><span class="unpaid">₹<?= number_format((float)$row['unpaid'], 2) ?></span></div>

                            <div data-label="Due Date">
                                <span class="date">
                                    <?php if ($dueText !== 'Not Set'): ?>
                                        <?= htmlspecialchars($dueText) ?>
                                    <?php else: ?>
                                        <span style="color:gray;">Not Set</span>
                                    <?php endif; ?>
                                </span>
                            </div>

                            <div data-label="Days Left">
                                <span class="days-left">
                                    <?php if ($daysText === 'Today'): ?>
                                        <span style="color:#d97706;">Today</span>
                                    <?php elseif (str_starts_with($daysText, 'Expired')): ?>
                                        <span class="expired"><?= htmlspecialchars($daysText) ?></span>
                                    <?php else: ?>
                                        <?= htmlspecialchars($daysText) ?>
                                    <?php endif; ?>
                                </span>
                            </div>

                            <div data-label="Action">
                                <a class="view-btn" href="invoice_view.php?id=<?= (int)$row['id'] ?>">View</a>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="no-data" id="noDataBox">✅ No Due Alerts</div>
                <?php endif; ?>
            </div>
        </div>

    </div>
</div>

<script>
const searchInput = document.getElementById('quickSearch');

if (searchInput) {
    searchInput.addEventListener('input', function () {
        const value = this.value.toLowerCase().trim();
        const rows = document.querySelectorAll('.grid-row.data');
        let visible = 0;

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

        const existingEmpty = document.getElementById('noDataBox');
        if (existingEmpty) {
            existingEmpty.style.display = visible === 0 ? 'block' : 'none';
        }

        let tempNoData = document.getElementById('tempNoData');
        if (!existingEmpty) {
            if (visible === 0) {
                if (!tempNoData) {
                    tempNoData = document.createElement('div');
                    tempNoData.id = 'tempNoData';
                    tempNoData.className = 'no-data';
                    tempNoData.textContent = 'No matching records found';
                    document.getElementById('rowsContainer').appendChild(tempNoData);
                }
            } else if (tempNoData) {
                tempNoData.remove();
            }
        }
    });
}
</script>

</body>
</html>