<div class="card mb-3">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <!-- From Date -->
            <div class="col-md-4">
                <!-- <label class="form-label">From Date</label> -->
                <input type="date" name="from_date" value="<?= $from_date ?>" class="form-control">
            </div>

            <!-- To Date -->
            <div class="col-md-4">
                <!-- <label class="form-label">To Date</label> -->
                <input type="date" name="to_date" value="<?= $to_date ?>" class="form-control">
            </div>

            <!-- Filter Button -->
            <div class="col-md-4 d-flex">
                <button class="btn btn-primary w-100 align-self-end">Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="row">
    <div class="col-md-9">
        <div class="row">
            <!-- Tokens -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-inline-flex align-items-center">
                                <i class="ph-duotone ph-ticket text-success me-2 f-20"></i>
                                <p class="text-muted mb-0">Tokens</p>
                            </div>
                            <h4 class="mb-0"><?= number_format($totalTokens) ?></h4>
                        </div>
                        <hr>
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-inline-flex align-items-center">
                                <i class="ph-duotone ph-currency-sign text-success me-2 f-20"></i>
                                <p class="text-muted mb-0">Amount</p>
                            </div>
                            <h4 class="mb-0"><?= amount_format_pakistani($totalAmount) ?></h4>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Funded Tokens -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-inline-flex align-items-center">
                                <i class="ph-duotone ph-hand-heart text-primary me-2 f-20"></i>
                                <p class="text-muted mb-0">Funded Tokens</p>
                            </div>
                            <h4 class="mb-0"><?= number_format($totalFundedTokens) ?></h4>
                        </div>
                        <hr>
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-inline-flex align-items-center">
                                <i class="ph-duotone ph-coins text-primary me-2 f-20"></i>
                                <p class="text-muted mb-0">Funded Amount</p>
                            </div>
                            <h4 class="mb-0"><?= amount_format_pakistani($totalFundedAmount) ?></h4>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Refunds & Discounts -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-body">
                        <!-- Refunds -->
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-inline-flex align-items-center">
                                <i class="ph-duotone ph-arrow-arc-left text-danger me-2 f-20"></i>
                                <p class="text-muted mb-0">Refunds</p>
                            </div>
                            <h4 class="mb-0"><?= amount_format_pakistani($totalRefund) ?></h4>
                        </div>
                        <hr>
                        <!-- Discounts -->
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-inline-flex align-items-center">
                                <i class="ph-duotone ph-tag text-warning me-2 f-20"></i>
                                <p class="text-muted mb-0">Discounts</p>
                            </div>
                            <h4 class="mb-0"><?= amount_format_pakistani($totalDiscount) ?></h4>
                        </div>
                    </div>
                </div>
            </div>
        </div> 
    </div>  

    <!-- Net Cash -->
    <div class="col-md-3">
        <?php 
            // Dynamic color: green if positive cash, red if zero or negative
            $cashColor = ($totalCash > 0) ? 'bg-success' : 'bg-danger';
        ?>
        <div class="card py-1 <?= $cashColor ?> text-white widget-visitor-card">
            <div class="card-body py-1 text-center">
                <h6 class="text-white">Net Cash</h6>
                <h4 class="text-white"><?= amount_format_pakistani($totalCash) ?></h3>
                <i class="material-icons-two-tone d-block f-46 text-white">payments</i>
                 <hr class="py-1">

            <!-- <h6>Due Amount</h6> -->
             <h4 class="text-white py-0 "><span>Due:</span> <?= amount_format_pakistani($totalDueAmount) ?></h4>
            </div>
        </div>
    </div>
</div>


<div class="row mb-3">



<div class="col-md-9">
    <div class="card">
<!--         <div class="card-header">
            <h5>Basic Tabs</h5>
        </div> -->
        <div class="card-body">

            <ul class="nav nav-tabs mb-3" role="tablist">
                <!-- Overall Tab -->
                <li class="nav-item">
                    <a class="nav-link active" data-bs-toggle="tab" href="#overallTab" role="tab">
                        Summary Report
                    </a>
                </li>

                <!-- Shift Tabs Dynamic -->
                <?php foreach ($shifts as $shift): ?>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#shift<?= $shift->id ?>" role="tab">
                            <?= $shift->name . ' Shift' ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>

            <div class="tab-content">
                <!-- Overall Tab Content -->
                <div class="tab-pane fade show active" id="overallTab" role="tabpanel">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped">
                                <thead class="">
                                    <tr>
                                        <th>Department</th>
                                        <!-- <th>Funded By</th> -->
                                       <!--  <?php foreach ($shifts as $shift): ?>
                                            <th><?= $shift->name ?></th>
                                        <?php endforeach; ?> -->
                                        <th>Total Tokens</th>
                                        <th>Total Amount</th>
                                        <th>Discount</th>
                                        <th>Refund</th>
                                        <th>Due</th>
                                        <th>Net Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($stats as $dept): ?>
                                        <?php foreach ($dept['sponsors'] as $sp): ?>
                                            <tr>
                                                <td><?= $dept['department_name'] ?>  <span class="badge bg-info"><?= $sp['funded_by'] ?></span></td>
                                                <!-- <td>
                                                    
                                       


                                                </td> -->

                                                <!-- <?php foreach ($shifts as $shift): ?>
                                                    <td><?= $sp['shifts'][$shift->id] ?? 0 ?></td>
                                                <?php endforeach; ?> -->

<?php
$total_amount   = $sp['total_amount'] ?? 0;
$total_discount = $sp['total_discount'] ?? 0;
$total_refund   = $sp['total_refund'] ?? 0;
$due_amount     = $sp['due_amount'] ?? 0;

$gross_total = $total_amount + $total_discount + $total_refund + $due_amount;
?>

<td><strong><?= $sp['total_tokens'] ?></strong></td>

<!-- Gross / Total Amount -->
<td class="fw-bold">
    <?= amount_format_pakistani($gross_total) ?>
</td>

<td class="text-danger">
    <?= amount_format_pakistani($total_discount) ?>
</td>

<td class="text-warning">
    <?= amount_format_pakistani($total_refund) ?>
</td>

<td class="text-danger fw-bold">
    <?= amount_format_pakistani($due_amount) ?>
</td>

<!-- Net Total -->
<td class="text-success fw-bold">
    <?= amount_format_pakistani($total_amount) ?>
</td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                
                </div>

                <!-- Shift Tabs Content -->
                <?php foreach ($shifts as $shift): ?>
                    <div class="tab-pane fade" id="shift<?= $shift->id ?>" role="tabpanel">
                        
<!--                             <div class="card-header">
                                <h5 class="mb-0"><?= $shift->name ?> Shift</h5>
                            </div> -->

                            <div class="table-responsive">
                                <table class="table table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Depart</th>
                                            <th>Tokens</th>
                                            <th>Amount</th>
                                            <th>Discount</th>
                                            <th>Refund</th>
                                            <th>Due</th>
                                            <th>Net Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($stats as $dept): ?>
                                            <?php foreach ($dept['sponsors'] as $sp): ?>

                                                <?php 
                                                $shiftTokens = $sp['shifts'][$shift->id] ?? 0;
                                                if ($shiftTokens == 0) continue;

                                                $perTokenAmount   = $sp['total_tokens'] > 0 ? $sp['total_amount'] / $sp['total_tokens'] : 0;
                                                $perTokenDiscount = $sp['total_tokens'] > 0 ? $sp['total_discount'] / $sp['total_tokens'] : 0;
                                                $perTokenRefund   = $sp['total_tokens'] > 0 ? $sp['total_refund'] / $sp['total_tokens'] : 0;
                                                $perTokenDue      = $sp['total_tokens'] > 0 ? $sp['due_amount'] / $sp['total_tokens'] : 0;
                                                $perTokenNet      = $sp['total_tokens'] > 0 ? $sp['net_total'] / $sp['total_tokens'] : 0;

                                                $shiftAmount   = $perTokenAmount * $shiftTokens;
                                                $shiftDiscount = $perTokenDiscount * $shiftTokens;
                                                $shiftRefund   = $perTokenRefund * $shiftTokens;
                                                $shiftDue      = $perTokenDue * $shiftTokens;
                                                $shiftNet      = $perTokenNet * $shiftTokens;
                                                ?>

                                                <tr>
                                                    <td>
                                                        <?= $dept['department_name'] ?>
                                                        <span class="badge bg-info"><?= $sp['funded_by'] ?></span>
                                                    </td>
                                                    <td><strong><?= $shiftTokens ?></strong></td>
                                                    <td><?= amount_format_pakistani($shiftAmount) ?></td>
                                                    <td class="text-danger"><?= amount_format_pakistani($shiftDiscount) ?></td>
                                                    <td class="text-warning"><?= amount_format_pakistani($shiftRefund) ?></td>
                                                    <td class="text-danger fw-bold"><?= amount_format_pakistani($shiftDue) ?></td>
                                                    <td class="text-success fw-bold"><?= amount_format_pakistani($shiftNet) ?></td>
                                                </tr>

                                            <?php endforeach; ?>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        
                    </div>
                <?php endforeach; ?>

            </div>
        </div>
    </div>
        <div class="card">
    <div class="card-body">
        <canvas id="amountChart"></canvas>   
    </div>
     </div>
</div>

<div class="col-md-3">
     <div class="card">
    <div class="card-body">
     <canvas id="tokenChart"></canvas>
    </div>


     </div>
     
     
</div>
</div>
<!-- ================= CHARTS ================= -->

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
const deptLabels = <?= json_encode($deptChartLabels) ?>;
const tokenData  = <?= json_encode($deptTokenData) ?>;

// ---------------- DONUT - TOKENS ----------------
new Chart(document.getElementById('tokenChart'), {
    type: 'doughnut',
    data: {
        labels: deptLabels,
        datasets: [{
            label: 'Tokens',
            data: tokenData,
            backgroundColor: deptLabels.map(() => 'rgba(54, 162, 235, 0.6)'),
            borderColor: deptLabels.map(() => 'rgba(54, 162, 235, 1)'),
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { position: 'bottom' }
        }
    }
});
</script>

<script>
// ---------------- STACKED BAR - NET AMOUNT SHIFT WISE ----------------
const deptShiftNet = <?= json_encode($deptShiftNet) ?>;
const shiftNames   = <?= json_encode($shiftNames) ?>;

const datasets = [];
const colors = [
    'rgba(255, 99, 132, 0.7)',   // Morning
    'rgba(54, 162, 235, 0.7)',   // Evening
    'rgba(255, 206, 86, 0.7)',   // Night
    'rgba(75, 192, 192, 0.7)',   // Extra shift
    'rgba(153, 102, 255, 0.7)'
];

let colorIndex = 0;

for (const shiftId in shiftNames) {
    const dataArr = [];

    deptLabels.forEach(dept => {
        if (deptShiftNet[dept] && deptShiftNet[dept][shiftId]) {
            dataArr.push(deptShiftNet[dept][shiftId]);
        } else {
            dataArr.push(0);
        }
    });

    datasets.push({
        label: shiftNames[shiftId],
        data: dataArr,
        backgroundColor: colors[colorIndex % colors.length]
    });

    colorIndex++;
}

new Chart(document.getElementById('amountChart'), {
    type: 'bar',
    data: {
        labels: deptLabels,
        datasets: datasets
    },
    options: {
        responsive: true,
        plugins: {
            legend: { position: 'bottom' }
        },
        scales: {
            x: { stacked: true },
            y: { stacked: true, beginAtZero: true }
        }
    }
});
</script>

