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

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

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

/*
    Show overdue alerts for BOTH panels:
    - sales_manager
    - sales_executive
    This does NOT depend on manager_id.
*/
$stmt = $conn->prepare("
    SELECT b.*,
           u.name AS created_by_name,
           u.role AS created_by_role,
           COALESCE(b.unpaid_due_date, b.due_date) AS final_due_date
    FROM bills b
    JOIN users u ON b.created_by = u.id
    WHERE (
        b.created_by = ?
        OR b.created_by IN (
            SELECT id FROM users WHERE manager_id = ?
        )
    )
    AND b.due_amount > 0
    AND (
        COALESCE(b.unpaid_due_date, b.due_date) < CURDATE()
        OR COALESCE(b.unpaid_due_date, b.due_date) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
    )
    ORDER BY final_due_date ASC
");

$stmt->bind_param("ii", $user_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
$alertCount = $result->num_rows;

function e($v) {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}
?>
<!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>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">

    <style>
        :root{
            --bg:#eef3f9;
            --card:#ffffff;
            --text:#0f172a;
            --muted:#64748b;
            --border:#dfe7f1;
            --shadow:0 16px 35px rgba(15, 23, 42, 0.08);
            --shadow-soft:0 10px 24px rgba(15, 23, 42, 0.06);
            --radius:18px;

            --primary:#374155;
            --danger:#dc2626;
            --success:#16a34a;
        }

        *{
            box-sizing:border-box;
        }

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

        a{
            text-decoration:none;
            color:inherit;
        }

        .main-content{
            margin-left:250px;
            margin-top:20px;
            min-height:calc(100vh - 20px);
        }

        .content{
            padding:14px 16px 16px;
            max-width:1600px;
        }

        .page-card{
            background:var(--card);
            border:1px solid var(--border);
            border-radius:18px;
            box-shadow:var(--shadow);
            padding:12px;
        }

        .page-title{
            background:transparent;
            border:none;
            box-shadow:none;
            padding:8px 0 12px;
            margin-bottom:0;
            display:flex;
            align-items:flex-start;
            justify-content:space-between;
            gap:12px;
            flex-wrap:wrap;
        }

        .title-left{
            display:flex;
            align-items:flex-start;
            gap:12px;
            min-width:0;
        }

        .title-icon{
            background:#eef2f7;
            color:#374155;
            width:36px;
            height:36px;
            display:flex;
            align-items:center;
            justify-content:center;
            border-radius:14px;
            font-size:14px;
            flex:0 0 auto;
            margin-top:2px;
        }

        .title-text h1{
            margin:0;
            font-size:22px;
            color:#0b1b3a;
            font-weight:700;
            letter-spacing:.2px;
            line-height:1.2;
        }

        .title-text p{
            margin:6px 0 0;
            color:var(--muted);
            font-size:13px;
            line-height:1.5;
        }

        .alert-badge{
            background:#374155;
            color:#fff;
            padding:8px 14px;
            border-radius:999px;
            font-size:13px;
            font-weight:700;
            white-space:nowrap;
            box-shadow:0 6px 14px rgba(32, 50, 74, 0.15);
            margin-top:2px;
        }

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

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

        .search-wrap i{
            font-style:normal;
            font-size:16px;
            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: 90px minmax(180px, 1.2fr) 160px 140px 130px 130px 140px 110px;
            align-items:center;
        
        }

        .grid-head{
            background:#374155;
            color:#fff;
            font-weight:700;
            text-transform:uppercase;
            letter-spacing:.3px;
            font-size:12px;
            border-radius:14px;
            overflow:hidden;
        }

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

        .grid-row{
            margin-top:10px;
            background:#fff;
            border:1px solid var(--border);
            border-radius:14px;
            box-shadow:0 1px 3px rgba(15,23,42,0.03);
        }

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

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

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

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

        .creator{
            display:flex;
            flex-direction:column;
            gap:4px;
            line-height:1.2;
        }

        .creator-name{
            font-weight:700;
            color:#111827;
        }

        .badge{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            padding:5px 10px;
            border-radius:999px;
            font-size:11px;
            font-weight:800;
            width:max-content;
            line-height:1;
        }

        .badge-manager{
            color:#000;
        }

        .badge-executive{
            color:#000;
        }

        .badge-other{
            background:#e5e7eb;
            color:#374151;
        }

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

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

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

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

        .view-btn{
            display:inline-block;
            background:#374155;
            color:#fff;
            text-decoration:none;
            padding:7px 12px;
            border-radius:10px;
            font-size:12px;
            font-weight:700;
            transition:.2s ease;
        }

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

        .no-data{
            text-align:center;
            padding:34px 10px;
            color:var(--success);
            font-weight:700;
            font-size:15px;
        }

        @media (max-width: 1100px){
            .main-content{
                margin-left:0;
                margin-top:20px;
            }
        }

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

    /* RESET */
    html, body{
        overflow-x: hidden;
    }

    .main-content{
        margin-left: 0 !important;
    }

    .content{
        padding: 12px;
    }

    /* TITLE */
    .title-text h1{
        font-size: 18px;
    }

    .title-text p{
        font-size: 12px;
    }

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

    /* SEARCH FULL */
    .search-wrap{
        width: 100%;
        min-width: 100%;
    }

    /* REMOVE GRID COMPLETELY */
    .grid-head{
        display: none;
    }

    .table-wrap{
        overflow: visible;
    }

    /* ✅ CARD UI */
    .grid-row{
        display: block !important;
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        padding: 14px;
        margin-bottom: 12px;
        box-shadow: 0 6px 16px rgba(0,0,0,0.05);
    }

    /* EACH ROW ITEM */
    .grid-row > div{
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 0;
        font-size: 13px;
        border-bottom: 1px dashed #eee;
    }

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

    /* LABELS */
    .grid-row > div::before{
        font-weight: 600;
        color: #64748b;
        font-size: 11px;
    }

    /* LABEL TEXT */
    .grid-row > div:nth-child(1)::before{ content: "Bill ID"; }
    .grid-row > div:nth-child(2)::before{ content: "Customer"; }
    .grid-row > div:nth-child(3)::before{ content: "Created By"; }
    .grid-row > div:nth-child(4)::before{ content: "Panel"; }
    .grid-row > div:nth-child(5)::before{ content: "Amount"; }
    .grid-row > div:nth-child(6)::before{ content: "Due Date"; }
    .grid-row > div:nth-child(7)::before{ content: "Status"; }
    .grid-row > div:nth-child(8)::before{ content: "Action"; }

    /* BILL STYLE */
    .bill-no{
        justify-content: center;
        font-weight: 900;
        font-size: 15px;
        border-bottom: 1px solid #ddd;
        margin-bottom: 6px;
        padding-bottom: 6px;
    }

    /* FIX CREATOR */
    .creator{
        display: block;
        text-align: right;
    }

    /* BUTTON */
    .view-btn{
        width: 100%;
        text-align: center;
    }
}
    </style>
</head>
<body>

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

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

            <div class="page-title">
                <div class="title-left">
                    <div class="title-icon">
                        <i class="fa-solid fa-bell"></i>
                    </div>
                    <div class="title-text">
                        <h1>Due Alert</h1>
                        <p>Sales manager and medical representative overdue bills</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 / 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>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 === 'medical_representative') {
    $panelLabel = 'Medical Representative';
    $panelClass = 'badge-executive';
}
 else {
                            $panelLabel = ucfirst(str_replace('_', ' ', $role ?: 'Other'));
                            $panelClass = 'badge-other';
                        }
                    ?>
                        <div class="grid-row" data-search="<?= e($searchText) ?>">
                            <div class="bill-no"><?= (int)$row['id'] ?></div>

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

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

                            <div>
                                <span class="badge <?= e($panelClass) ?>">
                                    <?= e($panelLabel) ?>
                                </span>
                            </div>

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

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

                            <div class="days-left">
                                <?php if ($daysText === 'Today'): ?>
                                    <span style="color:#d97706;">Today</span>
                                <?php else: ?>
                                    <span class="expired"><?= e($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>
            <?php else: ?>
                <div class="no-data">✅ No Due Alerts</div>
            <?php endif; ?>
        </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');

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

</body>
</html>