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

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

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

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

function esc($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function fetchSingleValue(mysqli $conn, string $sql, string $key, $default = 0) {
    $result = $conn->query($sql);
    if ($result && ($row = $result->fetch_assoc())) {
        return $row[$key] ?? $default;
    }
    return $default;
}

/* ===================== TEAM IDS ===================== */
$team_ids = [];

$stmt = $conn->prepare("SELECT id FROM users WHERE manager_id = ?");
$stmt->bind_param("i", $manager_id);
$stmt->execute();
$res = $stmt->get_result();

while ($row = $res->fetch_assoc()) {
    $team_ids[] = (int)$row['id'];
}
$stmt->close();

$team_ids[] = $manager_id;
$team_ids = array_values(array_unique(array_filter($team_ids)));

$team_ids_str = implode(',', array_map('intval', $team_ids));
if ($team_ids_str === '') {
    $team_ids_str = (string)$manager_id;
}

/* ===================== DASHBOARD METRICS ===================== */
$total_sales = fetchSingleValue(
    $conn,
    "SELECT COALESCE(SUM(total_amount),0) AS total
     FROM bills
     WHERE created_by IN ($team_ids_str)",
    'total',
    0
);

$total_received = fetchSingleValue(
    $conn,
    "SELECT COALESCE(SUM(advance_amount),0) AS total
     FROM bills
     WHERE created_by IN ($team_ids_str)",
    'total',
    0
);

$total_due = fetchSingleValue(
    $conn,
    "SELECT COALESCE(SUM(due_amount),0) AS total
     FROM bills
     WHERE created_by IN ($team_ids_str)",
    'total',
    0
);

$overdue = fetchSingleValue(
    $conn,
    "SELECT COALESCE(SUM(GREATEST(due_amount, 0)),0) AS overdue
     FROM bills
     WHERE due_date < CURDATE()
       AND created_by IN ($team_ids_str)
       AND GREATEST(due_amount, 0) > 0",
    'overdue',
    0
);

$total_bills = fetchSingleValue(
    $conn,
    "SELECT COUNT(*) AS total
     FROM bills
     WHERE created_by IN ($team_ids_str)",
    'total',
    0
);

$today_sales = fetchSingleValue(
    $conn,
    "SELECT COALESCE(SUM(total_amount),0) AS total
     FROM bills
     WHERE DATE(created_at) = CURDATE()
       AND created_by IN ($team_ids_str)",
    'total',
    0
);

$today_received = 0;

$active_team = fetchSingleValue(
    $conn,
    "SELECT COUNT(*) AS total
     FROM users
     WHERE manager_id = $manager_id",
    'total',
    0
);

/* ===================== LISTS ===================== */
$recent_bills = $conn->query("
    SELECT b.*, u.name AS user_name
    FROM bills b
    JOIN users u ON b.created_by = u.id
    WHERE b.created_by IN ($team_ids_str)
    ORDER BY b.id DESC
    LIMIT 8
");

$team_perf = $conn->query("
    SELECT 
        u.id,
        u.name,
        COUNT(b.id) AS bills_count,
        COALESCE(SUM(b.total_amount),0) AS sales,
        0 AS received,
        COALESCE(SUM(b.total_amount),0) AS due
    FROM users u
    LEFT JOIN bills b ON u.id = b.created_by
   WHERE u.manager_id = $manager_id 
AND u.role = 'medical_representative'
    GROUP BY u.id, u.name
    ORDER BY sales DESC, u.name ASC
");

$overdue_list = $conn->query("
    SELECT b.*, u.name AS user_name
    FROM bills b
    JOIN users u ON b.created_by = u.id
    WHERE b.due_date < CURDATE()
      AND b.created_by IN ($team_ids_str)
      AND GREATEST(b.total_amount, 0) > 0
    ORDER BY b.due_date ASC, b.id DESC
    LIMIT 6
");

$top_products = $conn->query("
    SELECT 
        p.product_name AS name,
        COALESCE(SUM(bi.qty),0) AS qty_sold,
        COALESCE(SUM(bi.qty * bi.price),0) AS value_sold
    FROM bill_items bi
    JOIN bills b ON bi.bill_id = b.id
    JOIN products p ON bi.product_id = p.id
    WHERE b.created_by IN ($team_ids_str)
    GROUP BY p.id, p.product_name
    ORDER BY qty_sold DESC
    LIMIT 5
");

/* ===================== SALES TREND ===================== */
$sales_trend = [];
$trend_res = $conn->query("
    SELECT DATE(created_at) AS day, COALESCE(SUM(total_amount),0) AS total
    FROM bills
    WHERE created_by IN ($team_ids_str)
      AND created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    GROUP BY DATE(created_at)
    ORDER BY day ASC
");

if ($trend_res) {
    while ($row = $trend_res->fetch_assoc()) {
        $sales_trend[$row['day']] = (float)$row['total'];
    }
}

$labels = [];
$values = [];
for ($i = 6; $i >= 0; $i--) {
    $day = date('Y-m-d', strtotime("-$i days"));
    $labels[] = date('d M', strtotime($day));
    $values[] = $sales_trend[$day] ?? 0;
}

$labels_json = json_encode($labels);
$values_json = json_encode($values);

$progress = $total_sales > 0 ? min(100, round(($total_received / $total_sales) * 100)) : 0;
$due_percent = $total_sales > 0 ? min(100, round(($total_due / $total_sales) * 100)) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Manager Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root{
            --bg:#f4f7fb;
            --card:#ffffff;
            --text:#0f172a;
            --muted:#64748b;
            --border:#e2e8f0;
            --primary:#2563eb;
            --primary-dark:#1d4ed8;
            --accent:#14b8a6;
            --success:#16a34a;
            --warning:#f59e0b;
            --danger:#ef4444;
            --shadow:0 10px 28px rgba(15,23,42,.08);
            --radius:16px;
            --sidebar-width:260px;
            --header-height:70px;
        }

        *{box-sizing:border-box}

        html, body{
            max-width:100%;
            overflow-x:hidden;
        }

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

        .content-area{
            margin-left:var(--sidebar-width);
            width:calc(100% - var(--sidebar-width));
            padding:24px 16px 16px !important;
            overflow-x:hidden;
        }

        .wrap{
            max-width:1580px;
            margin:0 auto;
        }

        .title{
            background:linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
            border:1px solid var(--border);
            border-radius:var(--radius);
            box-shadow:var(--shadow);
            padding:14px 16px;
            margin-bottom:18px;
        }

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

        .title h1 i{
            color:#000;
        }

        .title p{
            margin:8px 0 0;
            color:var(--muted);
            font-size:13px;
        }

        .header-actions{
            display:flex;
            gap:10px;
            flex-wrap:wrap;
        }

        .btn{
            display:inline-flex;
            align-items:center;
            gap:8px;
            text-decoration:none;
            border:none;
            cursor:pointer;
            padding:8px 12px;
            font-size:13px !important;
            border-radius:10px;
            font-weight:700;
            background:#fff;
            color:var(--text);
            box-shadow:var(--shadow);
        }

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

        .grid{
            display:grid;
            gap:14px;
        }

        .metrics{
            grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
            margin-bottom:16px;
            padding: 12px;
        }

        .card{
            background:var(--card);
            border:1px solid var(--border);
            border-radius:var(--radius);
            box-shadow:var(--shadow);
            min-width:0;
            position:relative;
            overflow:hidden;
        }

        /* ADD THIS */


.metric.green .value {
    color: #16a34a;
}



.metric.red .value {
    color: #dc2626;
}

        .metric{
            padding:12px;
        }

        .metric .label{
            color:var(--muted);
            font-size:11px;
            font-weight:800;
            text-transform:uppercase;
            letter-spacing:.05em;
        }

        .metric .value{
            font-size:20px;
            font-weight:900;
            color:var(--text);
            margin-top:10px;
            line-height:1.1;
        }

        .metric .sub{
            margin-top:8px;
            color:var(--muted);
            font-size:12px;
        }

        .row-2,
        .split{
            display:grid;
            grid-template-columns:minmax(0,1.2fr) minmax(0,.8fr);
            gap:14px;
            margin-bottom:14px;
            align-items:start;
        }

        .panel{
            padding:12px;
            min-width:0;
        }

        .panel h2{
            margin:0 0 14px;
            font-size:16px;
            color:var(--text);
        }

        .chart-box{
            width:100%;
            height:240px;
        }

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

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

        th, td{
            padding:9px 8px;
            border-bottom:1px solid var(--border);
            font-size:13px;
            text-align:left;
            white-space:nowrap;
            vertical-align:middle;
        }

        th{
            color:#334155;
            font-size:13px;
            background:#f8fafc;
        }

        td{
            color:var(--text);
            font-size:14px;
        }

        .badge{
            display:inline-flex;
            align-items:center;
            padding:5px 8px;
            border-radius:999px;
            font-size:11px;
            font-weight:700;
        }

        .badge.success{
            background:#ecfdf5;
            color:#15803d;
        }

        .badge.warning{
            background:#fffbeb;
            color:#b45309;
        }

        .badge.danger{
            background:#fef2f2;
            color:#dc2626;
        }

        .badge.neutral{
            background:#eff6ff;
            color:#1d4ed8;
        }

        .mini{
            padding:14px 0 6px;
        }

        .progress{
            height:10px;
            background:#e5e7eb;
            border-radius:999px;
            overflow:hidden;
            margin-top:12px;
        }

        .progress > div{
            height:100%;
            border-radius:999px;
        }

        .progress .paid{background:linear-gradient(90deg, var(--success), #22c55e);}
        .progress .due{background:linear-gradient(90deg, var(--warning), #fb7185);}

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

        .section-title{
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:10px;
            margin:0 0 12px;
            flex-wrap:wrap;
        }

        .section-title h2{
            margin:0;
            font-size:18px;
            color:var(--text);
        }

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

        @media (max-width: 992px){
            .content-area{
                margin-left:0;
                width:100%;
                padding-top:20px;
            }

            .row-2,
            .split{
                grid-template-columns:1fr;
            }

            table{
                min-width:700px;
            }
        }

        @media (max-width: 640px){
            .content-area{
                padding:14px;
            }

            .title{
                padding:16px;
            }

            .title h1{
                font-size:21px;
            }

            .metric .value{
                font-size:23px;
            }

            .panel{
                padding:14px;
            }
        }
        /* ================= MOBILE DASHBOARD FIX ================= */
@media (max-width:768px){

    /* MAIN AREA */
    .content-area{
        margin-left:0 !important;
        width:100% !important;
        padding:12px !important;
    }

    .wrap{
        max-width:100%;
    }

    /* TITLE */
    .title{
        padding:12px;
    }

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

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

    /* METRICS GRID */
    .metrics{
        grid-template-columns:1fr !important;
        gap:10px;
    }

    .metric{
        padding:12px;
    }

    .metric .value{
        font-size:18px;
    }

    /* CHART FIX */
    .chart-box{
        height:200px;
    }

    /* SPLIT SECTIONS */
    .row-2,
    .split{
        grid-template-columns:1fr !important;
        gap:12px;
    }

    /* 🔥 IMPROVED TABLE */
    .table-wrap{
        overflow-x:auto;
        -webkit-overflow-scrolling:touch;
        border-radius:12px;
    }

    table{
        min-width:520px; /* ✅ balanced width */
        width:100%;
        border-collapse:collapse;
    }

    /* HEADER */
    th{
        font-size:11px;
        padding:10px 6px;
        white-space:nowrap;
    }

    /* CELLS */
    td{
        font-size:12px;
        padding:10px 6px;
        white-space:nowrap; /* ✅ prevent break */
        word-break:keep-all;
    }

    /* FIX ₹ VALUE BREAK */
    td{
        letter-spacing:0.2px;
    }

    /* DATE SMALL */
    td:last-child{
        font-size:11px;
        color:#64748b;
    }

    /* BADGE */
    .badge{
        font-size:10px;
        padding:4px 6px;
        border-radius:8px;
        white-space:nowrap;
    }

    /* ROW CLEAN LOOK */
    tr{
        border-bottom:1px solid #eef2f7;
    }

    /* PANEL */
    .panel{
        padding:10px;
    }

    .panel h2{
        font-size:15px;
    }

}
    </style>
</head>
<body>

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

<main class="content-area">
    <div class="wrap">
        <div class="title">
            <h1>
                <i class="fas fa-chart-line"></i>
                Sales Manager Dashboard
            </h1>
            <p>Team sales, dues, overdue bills, and performance overview</p>
        </div>

        <div class="grid metrics">
            <div class="card metric green">
                <div class="label">Total Sales</div>
                <div class="value"><?= money($total_sales) ?></div>
                <div class="sub">All bills created by your team</div>
            </div>

            <div class="card metric green">
                <div class="label">Received</div>
                <div class="value"><?= money($total_received) ?></div>
                <div class="sub"><?= $progress ?>% of total sales collected</div>
            </div>

            <div class="card metric red">
                <div class="label">Total Due</div>
                <div class="value"><?= money($total_due) ?></div>
                <div class="sub"><?= $due_percent ?>% pending</div>
            </div>

            <div class="card metric red">
                <div class="label">Overdue</div>
                <div class="value"><?= money($overdue) ?></div>
                <div class="sub">Past due date amount</div>
            </div>

            <div class="card metric">
                <div class="label">Total Bills</div>
                <div class="value"><?= (int)$total_bills ?></div>
                <div class="sub">Created by you and your team</div>
            </div>

            <div class="card metric">
                <div class="label">Today Sales</div>
                <div class="value"><?= money($today_sales) ?></div>
                <div class="sub">Today's total billing</div>
            </div>

            <div class="card metric">
                <div class="label">Today Received</div>
                <div class="value"><?= money($today_received) ?></div>
                <div class="sub">Today's collection</div>
            </div>

            <div class="card metric">
                <div class="label">Team Members</div>
                <div class="value"><?= (int)$active_team ?></div>
                <div class="sub">Medical Representatives under this manager</div>
            </div>
        </div>

        <div class="row-2">
            <div class="card panel">
                <h2>Sales Trend (Last 7 Days)</h2>
                <div class="chart-box">
                    <canvas id="salesTrendChart"></canvas>
                </div>
            </div>

            <div class="card panel">
                <h2>Collection Status</h2>

                <div class="mini">
                    <div style="display:flex;justify-content:space-between;gap:10px;color:var(--text)">
                        <strong>Collected</strong>
                        <span><?= money($total_received) ?></span>
                    </div>
                    <div class="progress">
                        <div class="paid" style="width: <?= $progress ?>%;"></div>
                    </div>
                </div>

                <div class="mini">
                    <div style="display:flex;justify-content:space-between;gap:10px;color:var(--text)">
                        <strong>Pending Due</strong>
                        <span><?= money($total_due) ?></span>
                    </div>
                    <div class="progress">
                        <div class="due" style="width: <?= $due_percent ?>%;"></div>
                    </div>
                </div>

                <div class="mini">
                    <div style="display:flex;justify-content:space-between;gap:10px;color:var(--text)">
                        <strong>Overdue</strong>
                        <span><?= money($overdue) ?></span>
                    </div>
                    <div class="progress">
                        <div class="due" style="width: <?= $total_sales > 0 ? min(100, round(($overdue / $total_sales) * 100)) : 0 ?>%;"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="split">
            <div class="card panel">
                <div class="section-title">
                    <h2>Recent Bills</h2>
                    <div class="note">Latest team activity</div>
                </div>

                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User</th>
                                <th>Total</th>
                                <th>Paid</th>
                                <th>Due</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($recent_bills && $recent_bills->num_rows > 0): ?>
                            <?php while($b = $recent_bills->fetch_assoc()): ?>
                                <?php
                                    $bill_due = (float)($b['due_amount'] ?? 0);
                                    $paid_amt  = (float)($b['advance_amount'] ?? 0);

                                    if ($bill_due <= 0) {
                                        $statusClass = 'success';
                                        $statusText = 'Paid';
                                    } else {
                                        $statusClass = 'danger';
                                        $statusText = 'Pending';
                                    }
                                ?>
                                <tr>
                                    <td>#<?= (int)$b['id'] ?></td>
                                    <td><?= esc($b['user_name']) ?></td>
                                    <td><?= money($b['total_amount']) ?></td>
                                    <td><?= money($paid_amt) ?></td>
                                    <td>
                                        <span class="badge <?= $statusClass ?>">
                                            <?= money($bill_due) ?> / <?= $statusText ?>
                                        </span>
                                    </td>
                                    <td><?= esc($b['created_at']) ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="6" class="empty">No bills found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="card panel">
                <div class="section-title">
                    <h2>Overdue Bills</h2>
                    <div class="note">Needs follow-up</div>
                </div>

                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User</th>
                                <th>Due Date</th>
                                <th>Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($overdue_list && $overdue_list->num_rows > 0): ?>
                            <?php while($o = $overdue_list->fetch_assoc()): ?>
                                <?php $due_amt = max(0, (float)$o['total_amount']); ?>
                                <tr>
                                    <td>#<?= (int)$o['id'] ?></td>
                                    <td><?= esc($o['user_name']) ?></td>
                                    <td><?= esc($o['due_date']) ?></td>
                                    <td><span class="badge danger"><?= money($due_amt) ?></span></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="4" class="empty">No overdue bills.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="split">
            <div class="card panel">
                <div class="section-title">
                    <h2>Medical Representative Performance</h2>
                    <div class="note">By sales member</div>
                </div>

                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Bills</th>
                                <th>Sales</th>
                                <th>Received</th>
                                <th>Due</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($team_perf && $team_perf->num_rows > 0): ?>
                            <?php while($t = $team_perf->fetch_assoc()): ?>
                                <?php
                                    $sales = (float)$t['sales'];
                                    $received = (float)$t['received'];
                                    $due = (float)$t['due'];
                                ?>
                                <tr>
                                    <td><?= esc($t['name']) ?></td>
                                    <td><span class="badge neutral"><?= (int)$t['bills_count'] ?></span></td>
                                    <td><?= money($sales) ?></td>
                                    <td><?= money($received) ?></td>
                                    <td><span class="badge <?= $due > 0 ? 'warning' : 'success' ?>"><?= money($due) ?></span></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="empty">No team data found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="card panel">
                <div class="section-title">
                    <h2>Top Products</h2>
                    <div class="note">Best selling items</div>
                </div>

                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Qty Sold</th>
                                <th>Value</th>
                            </tr>
                        </thead>
                        <tbody> 
                        <?php if ($top_products && $top_products->num_rows > 0): ?>
                            <?php while($p = $top_products->fetch_assoc()): ?>
                                <tr>
                                    <td><?= esc($p['name']) ?></td>
                                    <td><span class="badge neutral"><?= (int)$p['qty_sold'] ?></span></td>
                                    <td><?= money($p['value_sold']) ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="3" class="empty">No product sales found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
const labels = <?= $labels_json ?>;
const values = <?= $values_json ?>;

new Chart(document.getElementById('salesTrendChart').getContext('2d'), {
    type: 'line',
    data: {
        labels: labels,
        datasets: [{
            data: values,
            tension: 0.35,
            fill: true,
            borderWidth: 2.5,
            pointRadius: 4,
            borderColor: '#2563eb',
            backgroundColor: 'rgba(37, 99, 235, 0.12)',
            pointBackgroundColor: '#14b8a6',
            pointBorderColor: '#ffffff',
            pointBorderWidth: 2
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: {
            y: {
                beginAtZero: true,
                grid: { color: '#e5e7eb' },
                ticks: { color: '#64748b' }
            },
            x: {
                grid: { display: false },
                ticks: { color: '#64748b' }
            }
        }
    }
});
</script>
</body>
</html>