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

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

function money($amount) {
    return "₹" . number_format((float)($amount ?? 0), 2);
}

// Total Bills
$total_bills = 0;
$stmt = $conn->prepare("SELECT COUNT(*) FROM bills WHERE created_by = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($total_bills);
$stmt->fetch();
$stmt->close();

// Today Sales
$today_sales = 0;
$stmt = $conn->prepare("
    SELECT COALESCE(SUM(total_amount), 0)
    FROM bills
    WHERE created_by = ? AND DATE(created_at) = CURDATE()
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($today_sales);
$stmt->fetch();
$stmt->close();


// Overdue Bills
$stmt = $conn->prepare("
    SELECT
        id,
        customer_name,
        total_amount,
        due_amount,
        payment_status,
        due_date
    FROM bills
    WHERE created_by = ?
      AND due_amount > 0
      AND due_date < CURDATE()
    ORDER BY due_date ASC
    LIMIT 8
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$overdue_bills = $stmt->get_result();

// Low Stock Products
$stmt = $conn->prepare("
    SELECT product_name, qty
    FROM products
    WHERE qty <= 10
    ORDER BY qty ASC
    LIMIT 8
");
$stmt->execute();
$low_stock = $stmt->get_result();

// Paid / Due / Advance
$total_paid = 0;
$total_due = 0;
$total_advance = 0;

$stmt = $conn->prepare("
    SELECT
        COALESCE(SUM(
            CASE
                WHEN payment_status = 'paid' THEN total_amount
                WHEN payment_status = 'advance' THEN advance_amount
                ELSE 0
            END
        ), 0) AS paid,
        COALESCE(SUM(due_amount), 0) AS due,
        COALESCE(SUM(CASE WHEN payment_status = 'advance' THEN advance_amount ELSE 0 END), 0) AS advance
    FROM bills
    WHERE created_by = ?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

$total_paid    = $result['paid'] ?? 0;
$total_due     = $result['due'] ?? 0;
$total_advance = $result['advance'] ?? 0;
$stmt->close();

// Overdue Bills
$overdue_count = 0;
$stmt = $conn->prepare("
    SELECT COUNT(*)
    FROM bills
    WHERE created_by = ?
      AND unpaid = 1
      AND unpaid_due_date < CURDATE()
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($overdue_count);
$stmt->fetch();
$stmt->close();

// Recent Bills
$stmt = $conn->prepare("
    SELECT
        id,
        customer_name,
        total_amount,
        advance_amount,
        due_amount,
        payment_status,
        due_date,
        created_at
    FROM bills
    WHERE created_by = ?
    ORDER BY id DESC
    LIMIT 10
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$recent_bills = $stmt->get_result();

// Top Products
$stmt = $conn->prepare("
    SELECT
        bi.product_name,
        COALESCE(SUM(bi.qty), 0) AS qty
    FROM bill_items bi
    INNER JOIN bills b ON bi.bill_id = b.id
    WHERE b.created_by = ?
    GROUP BY bi.product_name
    ORDER BY qty DESC
    LIMIT 5
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$top_products = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Medical Representative Dashboard</title>

    <style>
       :root{
    --bg:#f4f7fb;
    --card:#ffffff;
    --text:#1f2937;
    --muted:#6b7280;
    --line:#e5e7eb;

    --navy1:#071127;
    --navy2:#0f1724;
    --navy3:#111827;

    --primary:#3b82f6;
    --success:#198754;
    --warning:#fd7e14;
    --danger:#dc3545;

    --shadow:0 10px 30px rgba(2,6,23,.10);
    --shadow-soft:0 6px 18px rgba(2,6,23,.08);
    --radius:14px;
    --sidebar-width:260px;
    --header-height:65px;
}

*{ box-sizing:border-box; }

body{
    margin:0;
    font-family: Arial, sans-serif;
    background:
        radial-gradient(circle at top left, rgba(59,130,246,0.10), transparent 30%),
        linear-gradient(180deg, #eef4ff 0%, #f4f7fb 100%);
    color:var(--text);
}

.page-content{
    margin-left:var(--sidebar-width);
    padding:  26px 16px 16px;
    min-height:100vh;
}

.hero{
    background:#ffffff;
    color:#000;
    border-radius:14px;
    padding:14px 18px;
    box-shadow: 0 8px 22px rgba(2,6,23,0.18);
    margin-bottom:12px;
    position:relative;
    overflow:hidden;
    border:1px solid rgba(255,255,255,0.06);
}

.hero::before{
    content:"";
    position:absolute;
    top:-60px;
    right:-60px;
    width:180px;
    height:180px;
    border-radius:50%;
}

.hero::after{
    content:"";
    position:absolute;
    bottom:-60px;
    left:-60px;
    width:160px;
    height:160px;
    border-radius:50%;
}

.hero-inner{
    position:relative;
    z-index:1;
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
}

.hero h1{
    margin:0;
    font-size:20px;
    font-weight:700;
    letter-spacing:.2px;
    line-height:1.2;
}

.hero p{
    margin:5px 0 0;
    color:#374151;
    font-size:12px;
}

.hero h1 i{
    margin-right:8px;
    color:#111827;
    font-size:18px;
}

.hero-badge{
    background: rgba(59,130,246,0.15);
    border:1px solid rgba(59,130,246,0.35);
    padding:7px 12px;
    border-radius:999px;
    font-size:12px;
    color:#60a5fa;
    font-weight:600;
    white-space:nowrap;
}

.hero-chip{
    padding:8px 12px;
    border-radius:999px;
    background: rgba(255,255,255,0.08);
    border:1px solid rgba(255,255,255,0.10);
    font-size:12px;
    white-space:nowrap;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.06);
}

.cards{
    display:grid;
    grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));
    gap:12px;
    margin-bottom:14px;
}

.card{
    background: var(--card);
    border:1px solid rgba(229,231,235,0.9);
    border-radius: var(--radius);
    box-shadow: var(--shadow-soft);
    padding:14px;
    min-height:100px;
    display:flex;
    flex-direction:column;
    justify-content:space-between;
    transition: transform .18s ease, box-shadow .18s ease;
}

.card:hover{
    transform: translateY(-2px);
    box-shadow: var(--shadow);
}

.card h3{
    margin:0;
    font-size:13px;
    color:var(--muted);
    font-weight:700;
}

.card h2{
    margin:8px 0 0;
    font-size:22px;
    line-height:1.1;
}

.card small{
    margin-top:6px;
    color:var(--muted);
    font-size:11px;
}

.green{ color:var(--success); }
.red{ color:var(--danger); }
.blue{ color:var(--primary); }
.orange{ color:var(--warning); }

.actions{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    margin: 4px 0 14px;
}

.btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    padding:8px 12px;
    border-radius:10px;
    text-decoration:none;
    color:#fff;
    font-weight:700;
    font-size:13px;
    box-shadow:0 8px 20px rgba(0,0,0,0.08);
    transition: transform .16s ease, opacity .16s ease;
}

.btn:hover{
    transform: translateY(-1px);
    opacity:.96;
}

.btn i{
    font-size:14px;
}

.btn.primary{ background: linear-gradient(135deg, #2563eb, #3b82f6); }
.btn.success{ background: linear-gradient(135deg, #15803d, #22c55e); }
.btn.warning{ background: linear-gradient(135deg, #ea580c, #fb923c); }
.btn.secondary{ background: linear-gradient(135deg, #475569, #64748b); }

.grid-2{
    display:grid;
    grid-template-columns: minmax(0, 2fr) minmax(330px, 1fr);
    gap:12px;
    align-items:start;
}

.right-stack{
    display:flex;
    flex-direction:column;
    gap:12px;
    min-width:0;
}

.section{
    min-width:0;
    background: var(--card);
    border-radius: var(--radius);
    box-shadow: var(--shadow-soft);
    overflow:hidden;
    border:1px solid rgba(229,231,235,0.9);
}

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

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

.section-head h2{
    margin:0;
    font-size:16px;
    color:#111827;
}

.section-head span{
    color:var(--muted);
    font-size:12px;
}

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

th, td{
    color:#000;
    padding:10px 12px;
    border-bottom:1px solid #f1f5f9;
    text-align:left;
    white-space:nowrap;
    font-size:13px;
}

th{
    background:#f8fafc;
    color:#475569;
    font-weight:800;
}

tr:hover td{
    background:#fbfdff;
}

.badge{
    display:inline-block;
    padding:5px 9px;
    border-radius:999px;
    font-size:11px;
    font-weight:800;
}

.badge-paid{ color:#166534; background:#dcfce7; }
.badge-advance{ color:#92400e; background:#fef3c7; }
.badge-unpaid{ color:#991b1b; background:#fee2e2; }

.empty{
    padding:14px;
    color:var(--muted);
    font-size:13px;
}

.top-list{
    display:flex;
    flex-direction:column;
    gap:10px;
    padding:12px 14px 14px;
}

.product-row{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:10px;
    padding:10px 12px;
    border:1px solid #eef2f7;
    border-radius:12px;
    background:linear-gradient(180deg, #fff, #fbfdff);
}

.product-name{
    font-weight:700;
    color:#111827;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    font-size:13px;
}

.product-qty{
    font-weight:800;
    color:var(--primary);
    background:#eff6ff;
    padding:5px 9px;
    border-radius:999px;
    min-width:52px;
    text-align:center;
    font-size:12px;
}

.stats-strip{
    display:grid;
    grid-template-columns:repeat(4, minmax(0,1fr));
    gap:10px;
    margin-bottom:14px;
}

.mini{
    background: rgba(255,255,255,0.82);
    border:1px solid rgba(255,255,255,0.75);
    backdrop-filter: blur(8px);
    border-radius:12px;
    padding:10px 12px;
    box-shadow: var(--shadow-soft);
}

.mini .k{
    color:var(--muted);
    font-size:10px;
    font-weight:700;
    text-transform:uppercase;
    letter-spacing:.4px;
}

.mini .v{
    margin-top:6px;
    font-size:16px;
    font-weight:800;
    color:#111827;
}

.due-list,
.low-list{
    padding:12px;
    display:flex;
    flex-direction:column;
    gap:10px;
}

.due-card,
.low-card{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:10px 12px;
    border-radius:12px;
    background:#fff;
    border:1px solid #eee;
    transition:0.2s;
}

.due-card{
    border-left:4px solid #dc3545;
}

.low-card{
    border-left:4px solid #fd7e14;
}

.due-card:hover{
    background:#fff5f5;
}

.low-card:hover{
    background:#fff7e6;
}

.due-left{
    display:flex;
    flex-direction:column;
    gap:3px;
}

.due-customer,
.low-name{
    font-weight:600;
    font-size:14px;
    color:#111827;
}

.due-date{
    font-size:12px;
    color:#6b7280;
}

.due-right{
    background:#fde2e2;
    color:#dc3545;
    padding:5px 10px;
    border-radius:18px;
    font-weight:700;
    min-width:80px;
    text-align:center;
    font-size:12px;
}

.low-badge{
    background:#fff3cd;
    color:#fd7e14;
    padding:5px 10px;
    border-radius:18px;
    font-weight:700;
    min-width:52px;
    text-align:center;
    font-size:12px;
}

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

    .stats-strip{
        grid-template-columns:repeat(2, minmax(0,1fr));
    }
}

@media (max-width: 992px){
    .page-content{
        margin-left:0;
    }
}

@media (max-width: 768px){
    .page-content{
        padding: 76px 12px 12px;
    }

    .hero{
        padding:12px 14px;
    }

    .hero h1{
        font-size:18px;
    }

    .hero p{
        font-size:11px;
    }

    .card h2{
        font-size:20px;
    }

    .actions .btn{
        width:100%;
    }

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

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

<div class="page-content">

    <div class="hero">
        <div class="hero-inner">
            <div>
                <h1>
    <i class="fa-solid fa-chart-line"></i> 
   Medical Representative Dashboard
</h1>
                <p>Live summary of your bills, payments, dues, and sold products.</p>
            </div>
        </div>
    </div>

    <div class="stats-strip">
        <div class="mini">
            <div class="k">Total Bills</div>
            <div class="v"><?php echo (int)$total_bills; ?></div>
        </div>
        <div class="mini">
            <div class="k">Today Sales</div>
            <div class="v blue"><?php echo money($today_sales); ?></div>
        </div>
        <div class="mini">
            <div class="k">Overdue</div>
            <div class="v red"><?php echo (int)$overdue_count; ?></div>
        </div>
        <div class="mini">
            <div class="k">Advance</div>
            <div class="v orange"><?php echo money($total_advance); ?></div>
        </div>
    </div>

    <div class="cards">
        <div class="card">
            <div>
                <h3>Total Paid</h3>
                <h2 class="green"><?php echo money($total_paid); ?></h2>
            </div>
            <small>Collected amount</small>
        </div>

        <div class="card">
            <div>
                <h3>Total Due</h3>
                <h2 class="red"><?php echo money($total_due); ?></h2>
            </div>
            <small>Pending collection</small>
        </div>

        <div class="card">
            <div>
                <h3>Advance Received</h3>
                <h2 class="orange"><?php echo money($total_advance); ?></h2>
            </div>
            <small>Partial payments</small>
        </div>

       
    </div>

    <div class="actions">
        <a href="customer_info.php" class="btn primary">
    <i class="fa-solid fa-file-circle-plus"></i> Create Bill
</a>

<a href="sales_due_alerts.php" class="btn warning">
    <i class="fa-solid fa-triangle-exclamation"></i> View Due Alerts
</a>

<a href="sold_products.php" class="btn success">
    <i class="fa-solid fa-box-open"></i> Sold Products
</a>
    </div>

    <div class="grid-2">
    <div class="section">
        <div class="section-head">
            <h2>Recent Bills</h2>
            <span>Latest 10 entries</span>
        </div>
        <div class="table-wrap">
            <table>
                <tr>
                    <th>ID</th>
                    <th>Customer</th>
                    <th>Total</th>
                    <th>Paid</th>
                    <th>Due</th>
                    <th>Status</th>
                    <th>Due Date</th>
                </tr>

                <?php if ($recent_bills && $recent_bills->num_rows > 0): ?>
                    <?php while ($row = $recent_bills->fetch_assoc()):
                        $total   = (float)($row['total_amount'] ?? 0);
                        $advance = (float)($row['advance_amount'] ?? 0);
                        $due     = (float)($row['due_amount'] ?? 0);
                        $status  = $row['payment_status'] ?? 'unpaid';

                        if ($status === 'paid') {
                            $paid_display = $total;
                        } elseif ($status === 'advance') {
                            $paid_display = $advance;
                        } else {
                            $paid_display = 0;
                        }

                        if ($due <= 0 && $total > $paid_display) {
                            $due = $total - $paid_display;
                        }
                    ?>
                        <tr>
                            <td><?php echo (int)$row['id']; ?></td>
                            <td><?php echo htmlspecialchars($row['customer_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo money($total); ?></td>
                            <td class="green"><?php echo money($paid_display); ?></td>
                            <td class="red"><?php echo money($due); ?></td>
                            <td>
                                <?php if ($status === 'paid'): ?>
                                    <span class="badge badge-paid">Paid</span>
                                <?php elseif ($status === 'advance'): ?>
                                    <span class="badge badge-advance">Advance</span>
                                <?php else: ?>
                                    <span class="badge badge-unpaid">Unpaid</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($row['due_date'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="7" class="empty">No bills found.</td>
                    </tr>
                <?php endif; ?>
            </table>
        </div>
    </div>

    <div class="right-stack">
        <div class="section">
            <div class="section-head">
                <h2>Top Products</h2>
                <span>Most sold items</span>
            </div>
            <div class="top-list">
                <?php if ($top_products && $top_products->num_rows > 0): ?>
                    <?php while ($row = $top_products->fetch_assoc()): ?>
                        <div class="product-row">
                            <div class="product-name"><?php echo htmlspecialchars($row['product_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></div>
                            <div class="product-qty"><?php echo (int)($row['qty'] ?? 0); ?></div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="empty">No product sales found.</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="section">
            <div class="section-head">
                <h2>⚠ Due Alerts</h2>
                <span>Overdue bills</span>
            </div>

            <div class="due-list">
                <?php if ($overdue_bills && $overdue_bills->num_rows > 0): ?>
                    <?php while ($row = $overdue_bills->fetch_assoc()): ?>
                        <div class="due-card">
                            <div class="due-left">
                                <div class="due-customer">
                                    <?php echo htmlspecialchars($row['customer_name'] ?? 'No Name', ENT_QUOTES, 'UTF-8'); ?>
                                </div>
                                <div class="due-date">
                                    Due: <?php echo htmlspecialchars($row['due_date'] ?? '-', ENT_QUOTES, 'UTF-8'); ?>
                                </div>
                            </div>

                            <div class="due-right">
                                <?php echo money($row['due_amount'] ?? 0); ?>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="empty">No overdue bills 🎉</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="section">
            <div class="section-head">
                <h2>⚠ Low Stock</h2>
                <span>Running out products</span>
            </div>

            <div class="low-list">
                <?php if ($low_stock && $low_stock->num_rows > 0): ?>
                    <?php while ($row = $low_stock->fetch_assoc()): ?>
                        <div class="low-card">
                            <div class="low-name">
                                <?php echo htmlspecialchars($row['product_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>
                            </div>

                            <div class="low-badge">
                                <?php echo (int)($row['qty'] ?? 0); ?>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="empty">All products in stock ✅</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
</body>
</html>