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

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

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

/* ================== FETCH DATA ================== */

// LOW STOCK (threshold = 10)
$low_stock = [];
$q1 = $conn->query("
SELECT id, product_name, qty, units_per_packet 
FROM products 
WHERE IFNULL(qty,0) < IFNULL(units_per_packet,0)
ORDER BY qty ASC
");
if ($q1) {
    while ($row = $q1->fetch_assoc()) {
        $low_stock[] = $row;
    }
}

// EXPIRY ALERT (next 30 days)
$expiry = [];
$q2 = $conn->query("
    SELECT id, product_name, registration_exp_date
    FROM products
    WHERE registration_exp_date IS NOT NULL
      AND registration_exp_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    ORDER BY registration_exp_date ASC
");
if ($q2) {
    while ($row = $q2->fetch_assoc()) {
        $expiry[] = $row;
    }
}
// RENEWAL ALERT (next 30 days)
$renewal = [];
$q5 = $conn->query("
    SELECT id, product_name, renewal_process_start
    FROM products
    WHERE renewal_process_start IS NOT NULL
      AND renewal_process_start <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    ORDER BY renewal_process_start ASC
");

if ($q5) {
    while ($row = $q5->fetch_assoc()) {
        $renewal[] = $row;
    }
}

$renewalCount = count($renewal);
// UNPAID BILLS (role-based)
$dues = [];

$role = strtolower($_SESSION['role'] ?? '');
$userId = (int)($_SESSION['user_id'] ?? 0);

if ($role === 'medical_representative') {
    $q3 = $conn->query("
        SELECT id, customer_name, total_amount, created_at
        FROM bills
        WHERE payment_status = 'unpaid'
          AND mr_id = {$userId}
        ORDER BY created_at DESC
    ");
} elseif ($role === 'sales_manager') {
    $q3 = $conn->query("
        SELECT b.id, b.customer_name, b.total_amount, b.created_at
        FROM bills b
        INNER JOIN users u ON u.id = b.mr_id
        WHERE b.payment_status = 'unpaid'
          AND u.manager_id = {$userId}
        ORDER BY b.created_at DESC
    ");
} else {
    $q3 = $conn->query("
        SELECT id, customer_name, total_amount, created_at
        FROM bills
        WHERE payment_status = 'unpaid'
        ORDER BY created_at DESC
    ");
}

if ($q3) {
    while ($row = $q3->fetch_assoc()) {
        $dues[] = $row;
    }
}
if ($q3) {
    while ($row = $q3->fetch_assoc()) {
        $dues[] = $row;
    }
}

$ra_products = [];

$q4 = $conn->query("
    SELECT id, product_name, created_at
    FROM products
    WHERE notify_ra = 1
    ORDER BY id DESC
");

if ($q4) {
    while ($row = $q4->fetch_assoc()) {
        $ra_products[] = $row;
    }
}

$lowCount = count($low_stock);
$expiryCount = count($expiry);
$duesCount = count($dues);
$totalAlerts = $lowCount + $expiryCount + $duesCount + $renewalCount;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

    <style>
        :root{
            --bg: #ffffff;
            --surface: #ffffff;
            --text: #111111;
            --muted: #666666;
            --border: #e8e8e8;
            --shadow: 0 10px 30px rgba(0,0,0,.06);

            --low: #dc2626;
            --low-bg: rgba(220,38,38,.08);

            --exp: #d97706;
            --exp-bg: rgba(217,119,6,.08);

            --due: #2563eb;
            --due-bg: rgba(37,99,235,.08);

            --ok: #16a34a;
            --head: #f8fafc;
        }

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

        .page {
            padding: 24px;
            max-width: 1400px;
            margin: 0 auto;
        }

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

        .title-wrap h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 800;
            color: var(--text);
            letter-spacing: .2px;
        }

        .subtitle {
            margin-top: 6px;
            color: var(--muted);
            font-size: 14px;
        }

        .breadcrumb {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: var(--muted);
            font-size: 13px;
            margin-bottom: 10px;
        }

        .actions {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .pill {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 14px;
            border: 1px solid var(--border);
            border-radius: 999px;
            background: #fff;
            color: var(--text);
            box-shadow: 0 4px 14px rgba(0,0,0,.04);
            font-size: 14px;
            white-space: nowrap;
        }

        .pill strong { font-size: 15px; }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 16px;
            margin-bottom: 18px;
        }

        .card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: 18px;
            box-shadow: var(--shadow);
            padding: 18px;
            position: relative;
            overflow: hidden;
        }

        .card::before {
            content: "";
            position: absolute;
            inset: 0 auto 0 0;
            width: 5px;
            background: var(--border);
        }

        .card.low::before { background: var(--low); }
        .card.exp::before { background: var(--exp); }
        .card.due::before { background: var(--due); }
        .card.all::before { background: var(--ok); }

        .card-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
        }

        .card-label {
            margin: 0;
            color: var(--muted);
            font-size: 13px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: .6px;
        }

        .card-icon {
            width: 42px;
            height: 42px;
            border-radius: 12px;
            display: grid;
            place-items: center;
            background: #f8fafc;
            border: 1px solid var(--border);
            color: var(--text);
        }

        .card-value {
            margin: 12px 0 6px;
            font-size: 30px;
            font-weight: 800;
            line-height: 1;
        }

        .card-note {
            color: var(--muted);
            font-size: 13px;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 14px;
            flex-wrap: wrap;
            margin: 18px 0;
            padding: 16px;
            background: #fff;
            border: 1px solid var(--border);
            border-radius: 18px;
            box-shadow: var(--shadow);
        }

        .search-box {
            flex: 1;
            min-width: 260px;
            position: relative;
        }

        .search-box i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #888;
            font-size: 14px;
        }

        .search-box input {
            width: 100%;
            padding: 13px 14px 13px 42px;
            border: 1px solid var(--border);
            border-radius: 14px;
            outline: none;
            font-size: 14px;
            color: var(--text);
            background: #fff;
        }

        .search-box input:focus {
            border-color: #b5c7ff;
            box-shadow: 0 0 0 4px rgba(37,99,235,.08);
        }

        .legend {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .legend-item {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            color: var(--muted);
        }

        .dot {
            width: 10px;
            height: 10px;
            border-radius: 999px;
        }

        .dot.low { background: var(--low); }
        .dot.exp { background: var(--exp); }
        .dot.due { background: var(--due); }

        .section {
            background: #fff;
            border: 1px solid var(--border);
            border-radius: 20px;
            box-shadow: var(--shadow);
            overflow: hidden;
            margin-bottom: 18px;
        }

        .section-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 18px 18px 14px;
            border-bottom: 1px solid var(--border);
            background: var(--head);
            flex-wrap: wrap;
        }

        .section-title {
            display: flex;
            align-items: center;
            gap: 10px;
            margin: 0;
            font-size: 18px;
            font-weight: 800;
            color: var(--text);
        }

        .section-title .tag {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 32px;
            height: 32px;
            border-radius: 10px;
            color: #fff;
            font-size: 14px;
        }

        .tag.low { background: var(--low); }
        .tag.exp { background: var(--exp); }
        .tag.due { background: var(--due); }

        .section-badge {
            padding: 8px 12px;
            border-radius: 999px;
            font-size: 13px;
            font-weight: 700;
            background: #fff;
            border: 1px solid var(--border);
            color: var(--text);
        }

        .table-wrap {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 700px;
        }

        thead th {
            text-align: left;
            font-size: 13px;
            letter-spacing: .3px;
            text-transform: uppercase;
            color: #444;
            background: #fafafa;
            padding: 14px 16px;
            border-bottom: 1px solid var(--border);
        }

        tbody td {
            padding: 14px 16px;
            border-bottom: 1px solid #f0f0f0;
            color: var(--text);
            font-size: 14px;
            vertical-align: middle;
        }

        tbody tr:hover {
            background: #fafafa;
        }

        .row-low td:first-child,
        .row-low td:last-child,
        .text-low {
            color: var(--low);
            font-weight: 700;
        }

        .row-exp td:last-child,
        .text-exp {
            color: var(--exp);
            font-weight: 700;
        }

        .row-due td:nth-child(3),
        .text-due {
            color: var(--due);
            font-weight: 700;
        }

        .empty {
            padding: 28px 18px;
            text-align: center;
            color: var(--muted);
            font-size: 14px;
        }

        .badge {
            display: inline-flex;
            align-items: center;
            padding: 7px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: 700;
            border: 1px solid transparent;
        }
.back-btn{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:10px 14px;
    background:#374155;
    color:#fff;
    border-radius:10px;
    text-decoration:none;
    font-size:14px;
    font-weight:600;
    transition:0.3s;
}

.back-btn:hover{
    background:#1f2937;
}
        .badge.low { color: var(--low); background: var(--low-bg); border-color: rgba(220,38,38,.15); }
        .badge.exp { color: var(--exp); background: var(--exp-bg); border-color: rgba(217,119,6,.15); }
        .badge.due { color: var(--due); background: var(--due-bg); border-color: rgba(37,99,235,.15); }

        .muted { color: var(--muted); }

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

        @media (max-width: 640px) {
            .page { padding: 16px; }
            .summary-grid { grid-template-columns: 1fr; }
            .title-wrap h1 { font-size: 24px; }
            .toolbar { padding: 14px; }
            .section-head { padding: 14px; }
            tbody td, thead th { padding: 12px 14px; }
        }
    </style>
</head>
<body>
<div class="page">

    <div class="topbar">
        <div class="title-wrap">
            <div class="breadcrumb">
                <i class="fa-solid fa-house"></i>
                <span>Dashboard</span>
                <span>/</span>
                <span>Notifications</span>
            </div>
            <h1><i class="fa-solid fa-bell"></i> Notifications</h1>
            <div class="subtitle">Low stock, registration expiry, and unpaid due alerts in one place.</div>
        </div>

        <div class="actions">
        <a href="javascript:history.back()" class="back-btn">
    <i class="fa-solid fa-arrow-left"></i> Back
</a>
            <div class="pill"><i class="fa-solid fa-triangle-exclamation"></i> Total Alerts <strong><?php echo (int)$totalAlerts; ?></strong></div>
            <div class="pill"><i class="fa-solid fa-boxes-stacked"></i> Low Stock <strong><?php echo (int)$lowCount; ?></strong></div>
            <div class="pill"><i class="fa-solid fa-calendar-days"></i> Expiry <strong><?php echo (int)$expiryCount; ?></strong></div>
            <div class="pill"><i class="fa-solid fa-indian-rupee-sign"></i> Due <strong><?php echo (int)$duesCount; ?></strong></div>
        </div>
    </div>

  

      

    <div class="toolbar">
        <div class="search-box">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" id="search" placeholder="Search product, customer, date, amount...">
        </div>
        <div class="legend">
            <span class="legend-item"><span class="dot low"></span> Low stock</span>
            <span class="legend-item"><span class="dot exp"></span> Expiry</span>
            <span class="legend-item"><span class="dot due"></span> Unpaid due</span>
        </div>
    </div>

    <!-- LOW STOCK -->
    <div class="section" data-section="low">
        <div class="section-head">
            <h2 class="section-title"><span class="tag low"><i class="fa-solid fa-box"></i></span> Low Stock Alerts</h2>
            <div class="section-badge"><?php echo (int)$lowCount; ?> items</div>
        </div>

        <div class="table-wrap">
            <table id="lowTable">
                <thead>
                    <tr>
                        <th style="width:90px;">ID</th>
                        <th>Product</th>
                        <th style="width:160px;">Quantity</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!empty($low_stock)): ?>
                    <?php foreach ($low_stock as $p): ?>
                        <tr class="row-low">
                            <td><?php echo e($p['id']); ?></td>
                            <td><?php echo e($p['product_name']); ?></td>
                            <td><span class="badge low"><?php echo e($p['qty']); ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="3"><div class="empty">No low stock alerts right now.</div></td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- EXPIRY -->
    <div class="section" data-section="exp">
        <div class="section-head">
            <h2 class="section-title"><span class="tag exp"><i class="fa-solid fa-hourglass-half"></i></span> Expiry Alerts</h2>
            <div class="section-badge"><?php echo (int)$expiryCount; ?> items</div>
        </div>

        <div class="table-wrap">
            <table id="expTable">
                <thead>
                    <tr>
                        <th style="width:90px;">ID</th>
                        <th>Product</th>
                        <th style="width:180px;">Expiry Date</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!empty($expiry)): ?>
                    <?php foreach ($expiry as $e): ?>
                        <tr class="row-exp">
                            <td><?php echo e($e['id']); ?></td>
                            <td><?php echo e($e['product_name']); ?></td>
                            <td>
                                <span class="badge exp">
                                    <?php echo !empty($e['registration_exp_date']) ? date('d-m-Y', strtotime($e['registration_exp_date'])) : '-'; ?>
                                </span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="3"><div class="empty">No expiry alerts in the next 30 days.</div></td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <!-- RENEWAL ALERT -->
<div class="section" data-section="renewal">
    <div class="section-head">
        <h2 class="section-title">
            <span class="tag exp"><i class="fa-solid fa-repeat"></i></span>
            Renewal Alerts
        </h2>
        <div class="section-badge"><?php echo (int)$renewalCount; ?> items</div>
    </div>

    <div class="table-wrap">
        <table id="renewalTable">
            <thead>
                <tr>
                    <th style="width:90px;">ID</th>
                    <th>Product</th>
                    <th style="width:180px;">Renewal Start Date</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!empty($renewal)): ?>
                <?php foreach ($renewal as $r): ?>
                    <tr class="row-exp">
                        <td><?php echo e($r['id']); ?></td>
                        <td><?php echo e($r['product_name']); ?></td>
                        <td>
                            <span class="badge exp">
                                <?php echo date('d-m-Y', strtotime($r['renewal_process_start'])); ?>
                            </span>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="3">
                        <div class="empty">No renewal alerts in next 30 days.</div>
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

    <!-- DUES -->
    <div class="section" data-section="due">
        <div class="section-head">
            <h2 class="section-title"><span class="tag due"><i class="fa-solid fa-indian-rupee-sign"></i></span> Unpaid Due Alerts</h2>
            <div class="section-badge"><?php echo (int)$duesCount; ?> items</div>
        </div>

        <div class="table-wrap">
            <table id="dueTable">
                <thead>
                    <tr>
                        <th style="width:90px;">ID</th>
                        <th>Customer</th>
                        <th style="width:180px;">Amount</th>
                        <th style="width:160px;">Date</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!empty($dues)): ?>
                    <?php foreach ($dues as $d): ?>
                        <tr class="row-due">
                            <td><?php echo e($d['id']); ?></td>
                            <td><?php echo e($d['customer_name']); ?></td>
                            <td><span class="badge due">₹<?php echo number_format((float)$d['total_amount'], 2); ?></span></td>
                            <td><?php echo !empty($d['created_at']) ? date('d-m-Y', strtotime($d['created_at'])) : '-'; ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="4"><div class="empty">No unpaid dues found.</div></td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>


<div class="section">
    <div class="section-head">
        <h2 class="section-title">
            <span class="tag due"><i class="fa-solid fa-bell"></i></span>
            New Products (Admin)
        </h2>
        <div class="section-badge"><?php echo count($ra_products); ?> items</div>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Product</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!empty($ra_products)): ?>
                <?php foreach ($ra_products as $p): ?>
                    <tr>
                        <td><?php echo $p['id']; ?></td>
                        <td><?php echo e($p['product_name']); ?></td>
                        <td><?php echo date('d-m-Y', strtotime($p['created_at'])); ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="3">No new products</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
</div>

<script>
(function () {
    const search = document.getElementById('search');
    const tables = ['lowTable', 'expTable', 'renewalTable', 'dueTable'].map(id => document.getElementById(id));

    search.addEventListener('input', function () {
        const value = this.value.toLowerCase().trim();

        tables.forEach(table => {
            const rows = table.querySelectorAll('tbody tr');
            rows.forEach(row => {
                const text = row.innerText.toLowerCase();
                row.style.display = text.includes(value) ? '' : 'none';
            });
        });
    });
})();
</script>
</body>
</html>