<!DOCTYPE html>
<html lang="en">
<head>
  <?= view('shared/head') ?>
  <!-- Optionally include additional CSS -->
  <link rel="stylesheet" type="text/css" href="<?= base_url('css/library.css') ?>">
</head>

<body>
  <div class="wrapper">
    <!-- Navbar -->
    <?= view('layouts/navbar', ['menuItems' => $menuItems]) ?>

    <!-- Main Content -->
    <div class="content-wrapper p-4 text-navy">
      <h1>Commissions Paid</h1>

      <!-- Filters Row -->
      <form method="get" action="<?= base_url('commissionspaid') ?>" class="form-inline mb-3">
        <!-- Batch Filter -->
        <div class="form-group mr-3">
          <label for="batch_id" class="mr-2">Select Batch:</label>
          <select id="batch_id" name="batch_id" class="form-control" onchange="this.form.submit()">
            <?php if (!empty($distinctBatches)) : ?>
              <?php foreach ($distinctBatches as $batch): ?>
                <?php
                  // e.g. "2025-01-01 - 2025-01-31"
                  $displayText = $batch['from_date'] . ' - ' . $batch['to_date'];
                ?>
                <option value="<?= esc($batch['payout_batch']) ?>"
                  <?= ($selectedBatch == $batch['payout_batch']) ? 'selected' : '' ?>>
                  <?= esc($displayText) ?>
                </option>
              <?php endforeach; ?>
            <?php else: ?>
              <option>No batches found</option>
            <?php endif; ?>
          </select>
        </div>

        <!-- User Filter -->
        <div class="form-group">
          <label for="user_id" class="mr-2">User:</label>
          <select id="user_id" name="user_id" class="form-control" onchange="this.form.submit()">
            <!-- "All" Option -->
            <option value="all" <?= ($selectedUser === 'all') ? 'selected' : '' ?>>All</option>
            <!-- Distinct users for the selected batch -->
            <?php if (!empty($distinctUsers)) : ?>
              <?php foreach ($distinctUsers as $u): ?>
                <?php
                  $uid       = $u['user_id'];
                  $fullName  = trim($u['first_name'] . ' ' . $u['last_name']);
                ?>
                <option value="<?= esc($uid) ?>"
                  <?= ($selectedUser == $uid) ? 'selected' : '' ?>>
                  <?= esc($fullName) ?>
                </option>
              <?php endforeach; ?>
            <?php endif; ?>
          </select>
        </div>
      </form>

      <!-- Totals (top right) -->
      <div class="text-right mb-3">

        <!-- Per-user totals -->
        <?php if (!empty($amountsByUser)): ?>
          <h5>Totals by User (this period):</h5>
          <ul class="list-unstyled">
            <?php foreach ($amountsByUser as $uid => $userSummary): ?>
              <li>
                <!-- Make username clickable to open chart -->
                <strong>
                  <a href="#" class="showLineChart" data-userid="<?= esc($uid) ?>">
                    <?= esc($userSummary['name']) ?>:
                  </a>
                </strong>
                $<?= number_format($userSummary['total'], 2) ?>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>

        <!-- Overall total amount: also clickable for a "global" chart -->
        <h5>
          <a href="#" class="showLineChart" data-userid="all">
            Total Amount
          </a>
          :
          <span class="badge badge-success">
            <?= number_format($totalSum, 2) ?>
          </span>
        </h5>
      </div>

      <hr>

      <!-- Table of commission data: columns: User, Deal ID, Order ID, Job Function, Amount -->
      <?php if (!empty($dataForSelectedBatch)): ?>
        <table class="table table-bordered table-striped">
          <thead>
            <tr>
              <th>User</th>
              <th>Deal ID</th>
              <th>Order ID</th>
              <th>Job Function</th>
              <th>Amount</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($dataForSelectedBatch as $row): ?>
              <?php
                // Build full name
                $fullName = trim($row['first_name'] . ' ' . $row['last_name']) ?: 'Unknown';

                // Convert job_fuction_id to text
                switch ($row['job_fuction_id']) {
                  case 1:
                    $jobFunction = 'Deposit';
                    break;
                  case 2:
                    $jobFunction = 'Customer Care';
                    break;
                  case 3:
                    $jobFunction = 'Title Work';
                    break;
                  case 4:
                    $jobFunction = 'Complete Checkout';
                    break;
                  // For 5 or 6 => Upsells
                  case 5:
                  case 6:
                    $jobFunction = 'Upsells';
                    break;
                  default:
                    $jobFunction = 'Unknown';
                }
              ?>
              <tr>
                <td><?= esc($fullName) ?></td>
                <td><?= esc($row['deal_id']) ?></td>
                <td><?= esc($row['order_id']) ?></td>
                <td><?= esc($jobFunction) ?></td>
                <td><?= esc($row['amount']) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php else: ?>
        <p>No data found for the selected batch/user.</p>
      <?php endif; ?>
    </div>
  </div>

  <!-- JS scripts (Bootstrap & jQuery) -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

  <!-- Chart.js (CDN) -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <!-- Pass our batch & user totals data into global JS variables -->
  <script>
    window.batchesAsc = <?= json_encode($batchesAsc) ?>;  // array of {payout_batch, from_date, to_date} in ascending order
    window.lineTotals = <?= json_encode($lineTotals) ?>;   // user-specific sums: lineTotals[userId][payout_batch] = total
    window.allTotals  = <?= json_encode($allTotals) ?>;    // overall sums: allTotals[payout_batch] = total
  </script>

  <!-- Link our custom JS file (public/js/commissionspaid.js) -->
  <script src="<?= base_url('js/commissionspaid.js') ?>"></script>

  <!-- The Modal for showing the chart -->
  <div class="modal fade" id="chartModal" tabindex="-1" role="dialog" aria-labelledby="chartModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="chartModalLabel">Line Graph</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span>&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <canvas id="lineChart" width="400" height="200"></canvas>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
