<?php
// ---- Default date range ----
$today = date("Y-m-d");          // Today date
$monthStart = date("Y-m-01");    // first date of each month
$dFrom = $_GET['dFrom'] ?? $monthStart;
$dTo   = $_GET['dTo'] ?? $today;
?>

<div class="container mt-4">
  <div class="card shadow-lg p-4 rounded-3">
    <h4 class="mb-3">Commission Report</h4>
    <form method="get" class="row g-3">
        <div class="col-md-3">
            <label class="form-label">From</label>
            <input value="<?= $dFrom ?>" type="date" name="dFrom" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label">To</label>
            <input value="<?= $dTo ?>" type="date" name="dTo" class="form-control" required>
        </div>
        <div class="col-md-3 d-flex align-items-end" style="margin-top: 25px;">
            <button type="submit" class="btn btn-info w-100">Generate Report</button>
        </div>
    </form>
  </div>
</div>


<?php
function commission_report($dateFrom, $dateTo) {
    echo '<div class="container mt-4"> 
            <div class="alert alert-primary shadow-sm">
              <h5 class="mb-0">Commission Report: '.$dateFrom." → ".$dateTo.'</h5>
            </div>
          </div>';

    $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
    if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);

    // ---- Login user type check ----
    $loginType = $_SESSION['type'] ?? '';     //  login session-এ type আছে
    $loginId   = $_SESSION['user_id'];   // login user_id

    // ---- Base Query ----
    $sql = "SELECT u.user_id, u.user_name, u.comi_rate, COALESCE(SUM(t.AT_AMOUNT),0) as total_amount FROM `".$GLOBALS['arif_users']."` u LEFT JOIN `".$GLOBALS['arif_ac']."` a ON u.user_id = a.AA_AGENT LEFT JOIN `".$GLOBALS['arif_tran']."` t ON a.AA_ACNO = t.AT_ACID AND t.AT_TIMESTAMP BETWEEN '".$dateFrom." 00:00:00' AND '".$dateTo." 23:59:59' WHERE u.type = 'agent'";

    // ---- if Agent self data filter ----
    if ($loginType === 'agent') {
        $sql .= " AND u.user_id = '".$loginId."'";
    }

    $sql .= " GROUP BY u.user_id, u.user_name, u.comi_rate ORDER BY u.user_name ASC";

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

    echo '
    <div class="container mt-3">
    <div class="card shadow-sm rounded-3">
    <div class="card-body">
    <div class="table-responsive">
    <table class="table table-bordered table-hover align-middle">
      <thead class="table-light">
        <tr>
          <th>Agent ID</th>
          <th>Agent Name</th>
          <th>Total Collection</th>
          <th>Total Commission</th>
        </tr>
      </thead>
      <tbody>';

    $grandTotalCommission = 0;
    $grandTotalCollection = 0;

    if ($result && $result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $collection = $row["total_amount"];
            $commission = ($collection * $row["comi_rate"]) / 100;

            $grandTotalCollection += $collection;
            $grandTotalCommission += $commission;

            echo "
              <tr>
                <td>".$row["user_id"]."</td>
                <td>".$row["user_name"]."</td>
                <td>".number_format($collection,2)."</td>
                <td>".number_format($commission,2)."</td>
              </tr>";
        }
    } else {
        echo "<tr><td colspan='4' class='text-center text-muted'>No agents found</td></tr>";
    }

    echo '
      </tbody>
    </table>';

    // ---- if admin/bm then show grand total ----
    if ($loginType !== 'agent') {
        echo '<h5 class="text-end">
                Grand Total Collection : <b>'.number_format($grandTotalCollection,2).'</b><br>
                Grand Total Commission : <b>'.number_format($grandTotalCommission,2).'</b>
              </h5>';
    }

    echo '
    </div>
    </div>
    </div>
    ';

    $conn->close();
}

// ---- Call commission function ----
commission_report($dFrom, $dTo);
?>
