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

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

// ✅ Admin can see overdue bills from BOTH panels
/* PAGINATION */
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;

/* COUNT TOTAL */
$countQuery = $conn->query("
    SELECT COUNT(*) as total
    FROM bills b
    JOIN users u ON b.created_by = u.id
    WHERE u.role IN ('sales_manager', 'sales_executive')
      AND b.due_amount > 0
      AND b.payment_status IN ('unpaid','advance')
");

$total = $countQuery->fetch_assoc()['total'];
$totalPages = ceil($total / $limit);

/* MAIN QUERY WITH LIMIT */
$stmt = $conn->prepare("
    SELECT b.*,
           u.name AS created_by_name,
           u.role AS created_by_role,
           m.name AS manager_name,
           a.name AS agency_name,
           COALESCE(NULLIF(b.unpaid_due_date,'0000-00-00'), b.due_date) AS final_due_date
    FROM bills b
    JOIN users u ON b.created_by = u.id
    LEFT JOIN users m ON u.manager_id = m.id
    LEFT JOIN users a ON u.agency_id = a.id
    WHERE u.role IN ('sales_manager', 'sales_executive')
      AND b.due_amount > 0
      AND b.payment_status IN ('unpaid','advance')
    ORDER BY final_due_date ASC
    LIMIT ?, ?
");

$stmt->bind_param("ii", $start, $limit);
$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>Admin Due Alert</title>
    <style>
/* ===== ROOT ===== */
:root{
    --bg:#f4f6f9;
    --card:#ffffff;
    --head:#374155;
    --text:#0f172a;
    --muted:#6b7280;
    --border:#e5e7eb;
    --primary:#374155; 
    --danger:#ef4444;
    --success:#16a34a;
}

/* ===== RESET ===== */
*{box-sizing:border-box;}

body{
    margin:0;
    font-family:Inter, system-ui, Arial;
    background:var(--bg);
    color:var(--text);
}

/* ===== LAYOUT ===== */
.main-content{
    margin-left:260px;
    padding:12px;
}

/* ===== CARD ===== */
.page-card{
    background:var(--card);
    border-radius:14px;
    box-shadow:0 6px 18px rgba(0,0,0,0.05);
    padding:14px;
}

/* ===== HEADER ===== */
.page-header{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    margin-bottom:12px;
}

.page-title{
    font-size:20px;
    font-weight:800;
    margin:0;
}

.page-subtitle{
    font-size:12px;
    color:var(--muted);
    margin-top:2px;
}

/* ===== BADGE ===== */
.alert-badge{
    background:var(--primary);
    color:#fff;
    padding:6px 12px;
    border-radius:999px;
    font-weight:700;
    font-size:12px;
}

/* ===== SEARCH ===== */
.search-wrap{
    margin-bottom:12px;
    background:#fff;
    border:1px solid var(--border);
    border-radius:10px;
    padding:8px 12px;
}

.search-wrap input{
    border:none;
    outline:none;
    width:100%;
    font-size:12px;
}

/* ===== TABLE ===== */
.table-wrap{
    width:100%;
}

/* ===== GRID ===== */
.grid-head,
.grid-row{
    display:grid;
    grid-template-columns: 
    60px 1.3fr 140px 130px 140px 110px 130px 110px 90px;
    align-items:center;
}

/* ===== HEADER ===== */
.grid-head{
    background:linear-gradient(135deg,#374155,#1f2937);
    color:#fff;
    font-size:11px;
    font-weight:700;
    border-radius:10px;
}

.grid-head div{
    padding:8px;
}

/* ===== ROW ===== */
.grid-row{
    margin-top:8px;
    background:#fff;
    border:1px solid var(--border);
    border-radius:10px;
    font-size:12px;
    transition:.2s;
}

.grid-row:hover{
    transform:translateY(-1px);
    box-shadow:0 4px 12px rgba(0,0,0,0.04);
}

/* ===== CELLS ===== */
.grid-row div{
    padding:8px;
    display:flex;
    align-items:center;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

/* ===== ALIGNMENT ===== */
.grid-row div:nth-child(1),
.grid-row div:nth-child(4),
.grid-row div:nth-child(8),
.grid-row div:nth-child(9){
    justify-content:center;
    text-align:center;
}

/* ===== TEXT ===== */
.bill-no{ font-weight:800; }
.customer{ font-weight:700; }

.amount{
    color:var(--danger);
    font-weight:800;
}

.days-left{
    font-weight:700;
    color:var(--primary);
}

/* ===== BADGE ===== */
.expired{
    background:#fee2e2;
    color:#b91c1c;
    padding:4px 8px;
    border-radius:999px;
    font-size:10px;
    font-weight:700;
}

/* ===== BUTTON ===== */
.view-btn{
    background:var(--primary);
    color:#fff;
    padding:5px 10px;
    border-radius:8px;
    font-size:11px;
    font-weight:700;
    text-decoration:none;
    transition:.2s;
}

.view-btn:hover{
    background:#2f3848;
}

/* ===== EMPTY ===== */
.no-data{
    text-align:center;
    padding:20px;
    color:var(--success);
    font-weight:700;
    font-size:12px;
}

/* ===== AGENCY ===== */
.grid-row div:nth-child(5){
    font-weight:700;
    color:#374155;
}

/* ===== PAGINATION ===== */
.pagination{
    margin-top:12px;
    display:flex;
    justify-content:center;
    gap:6px;
}

.page-btn{
    padding:6px 10px;
    border-radius:8px;
    border:1px solid var(--border);
    background:#fff;
    color:var(--text);
    text-decoration:none;
    font-size:12px;
    font-weight:600;
}

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

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

/* ===== RESPONSIVE ===== */
@media(max-width:900px){
    .main-content{
        margin-left:0;
        padding:10px;
    }

    .grid-head,
    .grid-row{
        font-size:11px;
    }
}
  /* ================= MOBILE RESPONSIVE ================= */
@media (max-width: 768px) {

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

    /* CONTENT FULL WIDTH */
    .main-content {
        margin-left: 0 !important;
        padding: 0px;
    }

    /* HEADER */
    .page-header {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
    }

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

    .page-subtitle {
        font-size: 12px;
    }

    .alert-badge {
        font-size: 11px;
        padding: 5px 10px;
    }

    /* SEARCH */
    .search-wrap {
        padding: 6px 10px;
    }

    .search-wrap input {
        font-size: 12px;
    }

    /* 👉 IMPORTANT: GRID → SCROLLABLE */
    .table-wrap {
        overflow-x: auto;
    }

    /* GRID WIDTH FIX */
    .grid-head,
    .grid-row {
        min-width: 900px; /* important */
    }

    /* TEXT SMALL */
    .grid-head div,
    .grid-row div {
        font-size: 11px;
        padding: 6px;
    }

    /* BUTTON */
    .view-btn {
        font-size: 11px;
        padding: 4px 8px;
    }

    /* PAGINATION */
    .pagination {
        flex-wrap: wrap;
        gap: 5px;
    }

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

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

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

        <div class="page-header">
            <div class="title-block">
                <h1 class="page-title" style="color: #000;">Due Alert</h1>
                <p class="page-subtitle">Sales manager and  medical representativeoverdue bills</p>
            </div>

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

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

       <?php if ($alertCount > 0): ?>
    <div class="table-wrap">
        <div class="grid-head">
            <div>Bill</div>
            <div>Customer</div>
            <div>Created By</div>
            <div>Panel</div>
            <div>Agency</div>
            <div>Unpaid</div>
            <div>Due Date</div>
            <div>Days Left</div>
            <div>Action</div>
        </div>
 

                <?php while ($row = $result->fetch_assoc()): 
                    $dueText = 'N/A';
                    $daysText = 'N/A';

                    $searchText = strtolower(
                        ($row['id'] ?? '') . ' ' .
                        ($row['customer_name'] ?? '') . ' ' .
                        ($row['created_by_name'] ?? '') . ' ' .
                        ($row['created_by_role'] ?? '') . ' ' .
                        ($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';
                        }
                    }

                    $role = strtolower(trim($row['created_by_role'] ?? ''));
                    if ($role === 'sales_manager') {
                        $panelLabel = 'Sales Manager';
                        $panelClass = 'badge-manager';
                    } elseif ($role === 'sales_executive') {
                        $panelLabel = 'Sales Executive';
                        $panelClass = 'badge-executive';
                    } else {
                        $panelLabel = ucfirst(str_replace('_', ' ', $role ?: 'Other'));
                        $panelClass = 'badge-other';
                    }
                ?>
                    <div class="grid-row" data-search="<?= htmlspecialchars($searchText) ?>">
                        <div class="bill-no"><?= (int)$row['id'] ?></div>

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

                        <div class="creator">
                            <div class="creator-name">
                                <?= htmlspecialchars($row['created_by_name'] ?? 'N/A') ?>
                            </div>
                        </div>

                        <div>
                            <span class="badge <?= $panelClass ?>">
                                <?= htmlspecialchars($panelLabel) ?>
                            </span>
                        </div>
                          <div>
                            <?php
                            if($row['created_by_role'] == 'sales_executive'){
                                echo htmlspecialchars($row['manager_name'] ?? '-');
                            }elseif($row['created_by_role'] == 'sales_manager'){
                                echo htmlspecialchars($row['agency_name'] ?? '-');
                            }else{
                                echo '-';
                            }
                            ?>
                            </div>

                        <div class="amount">
                            ₹<?= number_format((float)$row['due_amount'], 2) ?>
                        </div>

                        <div class="date">
                            <?= htmlspecialchars($dueText) ?>
                        </div>

                        <div class="days-left">
                            <?php if ($daysText === 'Today'): ?>
                                <span style="color:#d97706;">Today</span>
                            <?php else: ?>
                                <span class="expired"><?= htmlspecialchars($daysText) ?></span>
                            <?php endif; ?>
                        </div>

                        <div>
                            <a href="invoice_view.php?id=<?= (int)$row['id'] ?>" class="view-btn">View</a>
                        </div>
                    </div>
                <?php endwhile; ?>
            </div>
              <div class="pagination">
    <?php if($page > 1): ?>
        <a href="?page=<?= $page-1 ?>" class="page-btn">Prev</a>
    <?php endif; ?>

    <?php for($i=1; $i <= $totalPages; $i++): ?>
        <a href="?page=<?= $i ?>" 
           class="page-btn <?= ($i == $page) ? 'active' : '' ?>">
           <?= $i ?>
        </a>
    <?php endfor; ?>

    <?php if($page < $totalPages): ?>
        <a href="?page=<?= $page+1 ?>" class="page-btn">Next</a>
    <?php endif; ?>
</div>
    </div>
<?php endif; ?>

    </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');

            rows.forEach(row => {
                const text = row.getAttribute('data-search') || '';
                row.style.display = text.includes(value) ? 'grid' : 'none';
            });
        });
    }
</script>
<script>
const slider = document.querySelector('.table-wrap');

let isDown = false;
let startX;
let scrollLeft;

slider.addEventListener('mousedown', (e) => {
    isDown = true;
    slider.classList.add('active');
    startX = e.pageX - slider.offsetLeft;
    scrollLeft = slider.scrollLeft;
});

slider.addEventListener('mouseleave', () => {
    isDown = false;
});

slider.addEventListener('mouseup', () => {
    isDown = false;
});

slider.addEventListener('mousemove', (e) => {
    if(!isDown) return;
    e.preventDefault();
    const x = e.pageX - slider.offsetLeft;
    const walk = (x - startX) * 2; // speed
    slider.scrollLeft = scrollLeft - walk;
});
</script>
</body>
</html>