<?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 e($v) {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

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

function fmt_date($d) {
    return !empty($d) ? date('d M Y, h:i A', strtotime($d)) : '-';
}

function build_url(array $params = []) : string {
    $query = array_merge($_GET, $params);
    foreach ($query as $k => $v) {
        if ($v === '' || $v === null) unset($query[$k]);
    }
    return '?' . http_build_query($query);
}

function csv_safe($value): string {
    $value = (string)($value ?? '');
    return preg_replace("/[\r\n]+/", ' ', $value);
}

/* ===================== FILTERS ===================== */
$date_from = trim($_GET['date_from'] ?? '');
$date_to   = trim($_GET['date_to'] ?? '');
$q         = trim($_GET['q'] ?? '');
$status    = trim($_GET['payment_status'] ?? 'all');
$range     = trim($_GET['range'] ?? '');

$today = date('Y-m-d');
$monthStart = date('Y-m-01');

if ($range === 'today') {
    $date_from = $today;
    $date_to = $today;
} elseif ($range === 'month') {
    $date_from = $monthStart;
    $date_to = $today;
}

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

$stmt = $conn->prepare("SELECT id FROM users WHERE manager_id = ?");
if ($stmt) {
    $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 = 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;
}

/* ===================== WHERE ===================== */
$where = "WHERE b.created_by IN ($team_ids_str)";

if ($q !== '') {
    $qEsc = $conn->real_escape_string($q);
    $where .= " AND (
        CAST(b.id AS CHAR) LIKE '%{$qEsc}%'
        OR b.customer_name LIKE '%{$qEsc}%'
        OR b.customer_gst LIKE '%{$qEsc}%'
        OR b.phone LIKE '%{$qEsc}%'
        OR u.name LIKE '%{$qEsc}%'
    )";
}

if ($status !== '' && $status !== 'all') {
    $statusEsc = $conn->real_escape_string($status);
    $where .= " AND b.payment_status = '{$statusEsc}'";
}

if ($date_from !== '') {
    $df = $conn->real_escape_string($date_from);
    $where .= " AND DATE(b.created_at) >= '{$df}'";
}

if ($date_to !== '') {
    $dt = $conn->real_escape_string($date_to);
    $where .= " AND DATE(b.created_at) <= '{$dt}'";
}

/* ===================== EXPORT CSV ===================== */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $exportSql = "
        SELECT
            b.id,
            b.customer_name,
            b.customer_gst,
            b.phone,
            b.subtotal,
            b.taxable_amount,
            b.sgst_amount,
            b.cgst_amount,
            b.total_amount,
            b.payment_status,
            b.created_at,
            u.name AS created_by_name
        FROM bills b
        LEFT JOIN users u ON b.created_by = u.id
        {$where}
        ORDER BY b.created_at DESC, b.id DESC
    ";

    $result = $conn->query($exportSql);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=sales_manager_report_' . date('Ymd_His') . '.csv');

    $out = fopen('php://output', 'w');
    fputcsv($out, ['Bill ID', 'Date', 'Customer', 'GST', 'Phone', 'Executive', 'Subtotal', 'Taxable', 'SGST', 'CGST', 'Total', 'Payment Status']);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            fputcsv($out, [
                $row['id'],
                $row['created_at'],
                csv_safe($row['customer_name']),
                csv_safe($row['customer_gst']),
                csv_safe($row['phone']),
                csv_safe($row['created_by_name']),
                $row['subtotal'],
                $row['taxable_amount'],
                $row['sgst_amount'],
                $row['cgst_amount'],
                $row['total_amount'],
                $row['payment_status'],
            ]);
        }
    }

    fclose($out);
    exit;
}

/* ===================== STATS ===================== */
$statsSql = "
    SELECT
        COUNT(*) AS total_bills,
        COALESCE(SUM(b.total_amount), 0) AS total_sales,
        COALESCE(SUM(CASE WHEN b.payment_status = 'paid' THEN 1 ELSE 0 END), 0) AS paid_bills,
        COALESCE(SUM(CASE WHEN b.payment_status = 'unpaid' THEN 1 ELSE 0 END), 0) AS unpaid_bills,
        COALESCE(SUM(CASE WHEN b.payment_status = 'advance' THEN 1 ELSE 0 END), 0) AS advance_bills
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    {$where}
";
$statsRes = $conn->query($statsSql);
$stats = $statsRes ? $statsRes->fetch_assoc() : [];

$total_bills   = (int)($stats['total_bills'] ?? 0);
$total_sales   = (float)($stats['total_sales'] ?? 0);
$paid_bills    = (int)($stats['paid_bills'] ?? 0);
$unpaid_bills  = (int)($stats['unpaid_bills'] ?? 0);
$advance_bills = (int)($stats['advance_bills'] ?? 0);

/* ===================== MAIN LIST ===================== */
$listSql = "
    SELECT
        b.id,
        b.customer_name,
        b.customer_gst,
        b.phone,
        b.subtotal,
        b.taxable_amount,
        b.sgst_amount,
        b.cgst_amount,
        b.total_amount,
        b.payment_status,
        b.created_at,
        b.created_by,
        u.name AS created_by_name
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    {$where}
    ORDER BY b.created_at DESC, b.id DESC
";
$listRes = $conn->query($listSql);
$recent_count = $listRes ? $listRes->num_rows : 0;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sales Manager Reports</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

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

    *{ 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:0 !important;
    padding-top:0 !important;
    }

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

    .page-title{
        background:transparent;
        border:none;
        box-shadow:none;
        padding:25px 0 10px;
        margin:0 0 8px;
    }

    .page-title h1{
        margin:0;
        font-size:22px;
        color:#0b1b3a;
        font-weight:700;
        letter-spacing:.2px;
        display:flex;
        align-items:center;
        gap:12px;
    }

    .page-title h1 i{
        background:#eef2f7;
        color:#374155;
        width:36px;
        height:36px;
        display:flex;
        align-items:center;
        justify-content:center;
        border-radius:14px;
        font-size:14px;
    }

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

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

    .quick-row{
        display:flex;
        gap:10px;
        flex-wrap:wrap;
        margin-bottom:12px;
    }

    .quick-btn{
        padding:8px 14px;
        border-radius:20px;
        background:#fff;
        border:1px solid #d1d5db;
        text-decoration:none;
        color:#000;
        font-size:13px;
        font-weight:600;
    }

    .quick-btn:hover{
        background:#f7f7f7;
    }

    .filter-box{
        background:#fff;
        border:1px solid #e5e7eb;
        border-radius:16px;
        padding:14px;
        margin-bottom:14px;
    }

    .filter-grid{
        display:grid;
        grid-template-columns:repeat(4, minmax(0, 1fr)) auto;
        gap:12px;
        align-items:end;
    }

    .filter-item{
        display:flex;
        flex-direction:column;
    }

    .filter-item label{
        font-size:12px;
        font-weight:700;
        margin-bottom:6px;
        color:#000;
    }

    .filter-item input,
    .filter-item select{
        padding:10px;
        border-radius:10px;
        border:1px solid #d1d5db;
        background:#fff;
        color:#000;
        outline:none;
        font-size:13px;
    }

    .filter-actions{
        display:flex;
        gap:8px;
        flex-wrap:wrap;
        align-items:end;
    }

    .btn-pill{
        border-radius:999px;
        padding:8px 14px;
        font-weight:700;
        text-decoration:none;
        display:inline-flex;
        align-items:center;
        gap:8px;
        border:1px solid #d1d5db;
        cursor:pointer;
        white-space:nowrap;
        background:#fff;
        color:#000;
        font-size:13px;
    }

    .btn-dark-pill{
        background:#374155;
        color:#fff;
        border-color:#374155;
    }

    .btn-dark-pill:hover{
        background:#273142;
        color:#fff;
    }

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

    .stat-card{
        background:linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
        border:1px solid var(--border);
        border-radius:18px;
        box-shadow:var(--shadow-soft);
        padding:12px;
        position:relative;
        overflow:hidden;
        min-height:90px;
    }

    .stat-card::before{
        content:'';
        position:absolute;
        inset:0 auto auto 0;
        width:100%;
        height:4px;
        background:linear-gradient(90deg, #374155, #6b7280);
    }

    .stat-label{
        color:var(--muted);
        font-size:10px;
        margin-bottom:4px;
        font-weight:800;
        text-transform:uppercase;
        letter-spacing:.04em;
    }

    .stat-value{
        font-size:18px;
        font-weight:900;
        color:#0f172a;
        line-height:1.1;
        word-break:break-word;
    }

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

    .muted{
        color:#555;
        font-size:13px;
    }

    .table-wrap{
        overflow:auto;
        border:1px solid #e5e7eb;
        border-radius:16px;
    }

    .table{
        width:100%;
        border-collapse:separate;
        border-spacing:0;
        margin:0;
    }

    .table thead th{
        background:#374155 !important;
        color:#fff !important;
        padding:10px 12px;
        font-size:12px;
        font-weight:800;
        border:0;
        white-space:nowrap;
        position:sticky;
        top:0;
        z-index:2;
        text-transform:uppercase;
        letter-spacing:.04em;
    }

    .table tbody td{
        padding:10px 12px;
        border-bottom:1px solid #eef2f7;
        white-space:nowrap;
        vertical-align:middle;
        font-size:13px;
        color:#000;
    }

    .table tbody tr:hover{
        background:#fafafa;
    }

    .badge-soft{
        padding:6px 10px;
        border-radius:999px;
        font-size:12px;
        font-weight:700;
        display:inline-block;
        text-transform:capitalize;
    }

    .paid{ background:#e5e7eb; color:#000; }
    .unpaid{ background:#f3f4f6; color:#000; }
    .advance{ background:#fde68a; color:#000; }

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

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

   @media (max-width: 768px){

    html, body{
        overflow-x: hidden;
    }

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

    .content{
        padding: 10px;
    }

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

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

    /* FILTER */
    .filter-grid{
        grid-template-columns: 1fr;
    }

    .filter-actions{
        width: 100%;
        justify-content: space-between;
    }

    .btn-pill{
        width: 100%;
        justify-content: center;
    }

    /* STATS */
    .stats-grid{
        grid-template-columns: 1fr;
    }

    /* ❌ HIDE TABLE HEADER */
    .table thead{
        display: none;
    }

    /* CARD VIEW */
    .table,
    .table tbody,
    .table tr,
    .table td{
        display: block;
        width: 100%;
    }

    .table tr{
        background: #fff;
        margin-bottom: 12px;
        padding: 12px;
        border-radius: 16px;
        border: 1px solid #e5e7eb;
        box-shadow: 0 6px 16px rgba(0,0,0,0.05);
    }

    .table td{
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 0;
        font-size: 13px;
        border-bottom: 1px dashed #eee;
    }

    .table td:last-child{
        border-bottom: none;
    }

    /* LABELS */
    .table td::before{
        font-weight: 600;
        color: #64748b;
        font-size: 11px;
    }

    /* LABEL TEXT */
    .table td:nth-child(1)::before{ content: "Bill ID"; }
    .table td:nth-child(2)::before{ content: "Date"; }
    .table td:nth-child(3)::before{ content: "Customer"; }
    .table td:nth-child(4)::before{ content: "GST"; }
    .table td:nth-child(5)::before{ content: "Phone"; }
    .table td:nth-child(6)::before{ content: "Executive"; }
    .table td:nth-child(7)::before{ content: "Subtotal"; }
    .table td:nth-child(8)::before{ content: "Taxable"; }
    .table td:nth-child(9)::before{ content: "Total"; }
    .table td:nth-child(10)::before{ content: "Status"; }

    /* STATUS BADGE CENTER */
    .badge-soft{
        font-size: 11px;
    }
}
</style>
</head>
<body>

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

<div class="main-content">
    <div class="content">
        <div class="page-title">
            <h1>
                <i class="fa-solid fa-chart-line"></i>
                Sales Reports
            </h1>
            <p>Team sales summary, executive-wise activity, and filtered bill history.</p>
        </div>

        <div class="page-card">
            <div class="quick-row">
                <a href="<?php echo e(build_url(['range' => 'today'])); ?>" class="quick-btn">Today</a>
                <a href="<?php echo e(build_url(['range' => 'month'])); ?>" class="quick-btn">This Month</a>
                <a href="reports.php" class="quick-btn">All</a>
            </div>

            <form method="GET" class="filter-box">
                <div class="filter-grid">
                    <div class="filter-item">
                        <label>Search</label>
                        <input type="text" name="q" value="<?php echo e($q); ?>">
                    </div>

                    <div class="filter-item">
                        <label>From</label>
                        <input type="date" name="date_from" value="<?php echo e($date_from); ?>">
                    </div>

                    <div class="filter-item">
                        <label>To</label>
                        <input type="date" name="date_to" value="<?php echo e($date_to); ?>">
                    </div>

                    <div class="filter-item">
                        <label>Status</label>
                        <select name="payment_status">
                            <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All</option>
                            <option value="paid" <?php echo $status === 'paid' ? 'selected' : ''; ?>>Paid</option>
                            <option value="unpaid" <?php echo $status === 'unpaid' ? 'selected' : ''; ?>>Unpaid</option>
                            <option value="advance" <?php echo $status === 'advance' ? 'selected' : ''; ?>>Advance</option>
                        </select>
                    </div>

                    <div class="filter-actions">
                        <button type="submit" class="btn-pill btn-dark-pill">Search</button>
                        <a href="<?php echo e(build_url(['export' => 'csv'])); ?>" class="btn-pill btn-dark-pill">
                            <i class="fa-solid fa-file-csv"></i> Export
                        </a>
                    </div>
                </div>
            </form>

            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-label">Total Bills</div>
                    <div class="stat-value"><?php echo (int)$total_bills; ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-label">Total Sales</div>
                    <div class="stat-value"><?php echo money($total_sales); ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-label">Paid Bills</div>
                    <div class="stat-value"><?php echo (int)$paid_bills; ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-label">Unpaid / Advance</div>
                    <div class="stat-value"><?php echo (int)$unpaid_bills; ?> / <?php echo (int)$advance_bills; ?></div>
                </div>
            </div>

            <div class="table-headline">
                <div class="fw-bold text-dark">Showing <?php echo (int)$recent_count; ?> record(s)</div>
                <div class="muted">Manager team wise report</div>
            </div>

            <div class="table-wrap">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Bill ID</th>
                            <th>Date &amp; Time</th>
                            <th>Customer</th>
                            <th>GST</th>
                            <th>Phone</th>
                            <th>Executive</th>
                            <th>Subtotal</th>
                            <th>Taxable</th>
                            <th>Total</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if ($listRes && $listRes->num_rows > 0): ?>
                        <?php while ($row = $listRes->fetch_assoc()): ?>
                            <?php $st = strtolower((string)($row['payment_status'] ?? 'unpaid')); ?>
                            <tr>
                                <td>#<?php echo (int)$row['id']; ?></td>
                                <td><?php echo e(fmt_date($row['created_at'])); ?></td>
                                <td><?php echo e($row['customer_name'] ?: '-'); ?></td>
                                <td><?php echo e($row['customer_gst'] ?: '-'); ?></td>
                                <td><?php echo e($row['phone'] ?: '-'); ?></td>
                                <td><?php echo e($row['created_by_name'] ?: '-'); ?></td>
                                <td><?php echo money($row['subtotal'] ?? 0); ?></td>
                                <td><?php echo money($row['taxable_amount'] ?? 0); ?></td>
                                <td><strong><?php echo money($row['total_amount'] ?? 0); ?></strong></td>
                                <td>
                                    <span class="badge-soft <?php echo in_array($st, ['paid','unpaid','advance'], true) ? $st : 'unpaid'; ?>">
                                        <?php echo e(ucfirst($st)); ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="10" style="text-align:center;padding:18px;color:#64748b;">No report data found.</td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

</body>
</html>