<?php
// tamdid_report_R_table.php  (R1..R12 + banner) + Shabnam font + phone 'wait' filter

// ---------- API: grouped report by type (R1..R12 + banner) ----------
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['from']) && isset($_GET['to']) && (isset($_GET['asJson']) || isset($_GET['ajax']))) {

    header("Content-Type: application/json; charset=utf-8");

    include '../../../utils/database.php';
    include '../../../utils/helper.php';

    $from = $_GET["from"];
    $to   = $_GET["to"];
    $typeSel = $_GET["type"] ?? 'normal'; // normal | drop

    // Parse Shamsi like 1403Y12M01D
    $yearFrom  = substr($from, 0, 4);
    $monthFrom = getBetween($from, "Y", "M");
    $dayFrom   = getBetween($from, "M", "D");

    $yearTo  = substr($to, 0, 4);
    $monthTo = getBetween($to, "Y", "M");
    $dayTo   = getBetween($to, "M", "D");

    $fromTs = currentTsToPaymentTs(shamsiToTs($yearFrom, $monthFrom, $dayFrom));
    $toTs   = currentTsToPaymentTs(shamsiToTs($yearTo,   $monthTo,   $dayTo)) + 86399; // انتهای روز مقصد

    $tableName = ($typeSel === "drop") ? "tamdidDrop" : "tamdid";

    // DB
    $conn = new mysqli($servername, $username, $password, $dbname_process);
    mysqli_set_charset($conn, "utf8");
    if ($conn->connect_error) {
        echo json_encode(["error" => "Connection failed: " . $conn->connect_error]);
        exit;
    }

    // group by type (R1..R12 + banner) و حذف phone='wait'
    $sql = "
      SELECT `type` AS grp,
             COUNT(*)             AS clicks,
             SUM(`isSeen`=1)      AS seen,
             SUM(`isInGateway`=1) AS inGateway,
             SUM(`isPay`=1)       AS paid
      FROM `$tableName`
      WHERE `createdAt` BETWEEN $fromTs AND $toTs
        AND COALESCE(LOWER(TRIM(`phone`)), '') <> 'wait'
        AND `type` NOT IN ('direct','tamdid','new')
        AND ( UPPER(`type`) REGEXP '^R([1-9]|1[0-2])$' OR LOWER(`type`) = 'banner' )
      GROUP BY `type`
      ORDER BY
        CASE
          WHEN `type`='R1'  THEN 1  WHEN `type`='R2'  THEN 2  WHEN `type`='R3'  THEN 3
          WHEN `type`='R4'  THEN 4  WHEN `type`='R5'  THEN 5  WHEN `type`='R6'  THEN 6
          WHEN `type`='R7'  THEN 7  WHEN `type`='R8'  THEN 8  WHEN `type`='R9'  THEN 9
          WHEN `type`='R10' THEN 10 WHEN `type`='R11' THEN 11 WHEN `type`='R12' THEN 12
          WHEN LOWER(`type`)='banner' THEN 13
          ELSE 999
        END
    ";

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

    // اسکلت: R1..R12 + banner با صفر
    $rows = [];
    for ($i = 1; $i <= 12; $i++) {
        $rows["R$i"] = ["grp"=>"R$i","clicks"=>0,"seen"=>0,"inGateway"=>0,"paid"=>0];
    }
    $rows["banner"] = ["grp"=>"banner","clicks"=>0,"seen"=>0,"inGateway"=>0,"paid"=>0];

    if ($result === false) {
        echo json_encode([
          "error"  => "SQL error: " . $conn->error,
          "data"   => array_values($rows),
          "totals" => ["clicks"=>0,"seen"=>0,"inGateway"=>0,"paid"=>0]
        ]);
        exit;
    }

    while ($r = $result->fetch_assoc()) {
        $k = (strtolower($r["grp"]) === 'banner') ? 'banner' : $r["grp"];
        if (isset($rows[$k])) {
            $rows[$k]["clicks"]    = (int)$r["clicks"];
            $rows[$k]["seen"]      = (int)$r["seen"];
            $rows[$k]["inGateway"] = (int)$r["inGateway"];
            $rows[$k]["paid"]      = (int)$r["paid"];
        }
    }

    $totals = ["clicks"=>0, "seen"=>0, "inGateway"=>0, "paid"=>0];
    foreach ($rows as $r) {
        $totals["clicks"]    += $r["clicks"];
        $totals["seen"]      += $r["seen"];
        $totals["inGateway"] += $r["inGateway"];
        $totals["paid"]      += $r["paid"];
    }

    echo json_encode(["data"=>array_values($rows), "totals"=>$totals]);
    exit;
}
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
  <meta charset="UTF-8" />
  <title>داشبورد R1..R12 + banner | Tamdid</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <!-- Bootstrap RTL -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
  <!-- Bootstrap Icons -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

  <style>
    /* ====== Shabnam Font (from ../../../utils/fonts/) ====== */
    @font-face{
      font-family: 'Shabnam';
      src: url('../../../utils/fonts/Shabnam.woff2') format('woff2'),
           url('../../../utils/fonts/Shabnam.woff') format('woff'),
           url('../../../utils/fonts/Shabnam.ttf') format('truetype');
      font-weight: 400;
      font-style: normal;
      font-display: swap;
    }
    @font-face{
      font-family: 'Shabnam';
      src: url('../../../utils/fonts/Shabnam.woff2') format('woff2'),
           url('../../../utils/fonts/Shabnam.woff') format('woff'),
           url('../../../utils/fonts/Shabnam.ttf') format('truetype');
      font-weight: 700;
      font-style: normal;
      font-display: swap;
    }

    /* ====== Base styles ====== */
    :root{
      --md-bg:#f6f8fb;
      --md-title:#0f172a;
      --md-chip-bg:#eef2ff;
      --md-chip-fg:#3730a3;
      --md-thead:#f1f5f9;
      --md-thead-border:#e2e8f0;
      --md-focus:#3f51b5;
    }
    html, body { height: 100%; }
    body{
      background: var(--md-bg);
      font-family: 'Shabnam', system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
    .app-title{ color: var(--md-title); }
    .card-md{
      border:0;border-radius:18px;
      box-shadow:0 10px 30px rgba(2,6,23,.07)
    }
    .md-input:focus{
      border-color: var(--md-focus) !important;
      box-shadow: 0 0 0 .2rem rgba(63,81,181,.12) !important;
    }
    .btn-md{ border-radius:999px; padding:.65rem 1.2rem }
    .table thead th{
      background: var(--md-thead);
      color: var(--md-title);
      font-weight:700;
      border-bottom:2px solid var(--md-thead-border);
    }
    .stat-chip{
      background: var(--md-chip-bg);
      color: var(--md-chip-fg);
      border-radius:999px;
      padding:.4rem .7rem;
      font-weight:700;
      letter-spacing:.2px;
    }
    .footer-note{ color:#64748b; font-size:.9rem }
    .spinner{ display:none }
  </style>
</head>
<body>
  <div class="container py-5">
    <h3 class="text-center app-title mb-4">📊 گزارش R1 تا R12 + banner (کلیک / دیده‌شدن / درگاه / پرداخت)</h3>

    <!-- Filters -->
    <div class="card card-md p-4 mb-4">
      <form id="filterForm" class="row gy-3 gx-3 align-items-end">
        <div class="col-md-4">
          <label class="form-label">از تاریخ (مثال: 1403Y12M01D)</label>
          <input type="text" name="from" class="form-control md-input" required>
        </div>
        <div class="col-md-4">
          <label class="form-label">تا تاریخ (مثال: 1403Y12M29D)</label>
          <input type="text" name="to" class="form-control md-input" required>
        </div>
        <div class="col-md-3">
          <label class="form-label">نوع جدول</label>
          <select name="type" class="form-select md-input">
            <option value="normal">Normal</option>
            <option value="drop">Drop</option>
          </select>
        </div>
        <div class="col-md-1 d-grid">
          <button class="btn btn-primary btn-md" type="submit">
            <span class="spinner-border spinner-border-sm me-1 spinner" id="btnSpin" role="status" aria-hidden="true"></span>
            <i class="bi bi-funnel me-1"></i> فیلتر
          </button>
        </div>
      </form>
    </div>

    <!-- Results -->
    <div class="card card-md p-3">
      <div class="d-flex justify-content-between align-items-center px-2 pt-2 pb-0">
        <h5 class="m-0">نتایج</h5>
        <div class="d-flex gap-2 flex-wrap">
          <span class="stat-chip" id="totalClicks">کلیک: 0</span>
          <span class="stat-chip" id="totalSeen">دیده‌شدن: 0</span>
          <span class="stat-chip" id="totalGateway">درگاه: 0</span>
          <span class="stat-chip" id="totalPaid">پرداخت: 0</span>
        </div>
      </div>

      <div class="table-responsive mt-3">
        <table class="table table-hover align-middle" id="resultTable">
          <thead>
            <tr>
              <th style="width:90px">گروه</th>
              <th>کلیک‌ها</th>
              <th>دیده‌شدن</th>
              <th>ورود به درگاه</th>
              <th>پرداخت</th>
              <th style="width:230px">نسبت‌ها</th>
            </tr>
          </thead>
          <tbody><!-- rows inject --></tbody>
        </table>
      </div>

      <div class="px-2 pb-2 footer-note">
        نسبت‌ها: Seen/Click، Gateway/Seen، Pay/Gateway (اگر مخرج صفر باشد «—» نمایش داده می‌شود).
      </div>
    </div>
  </div>

  <!-- Axios -->
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    function fmtPercent(num, den){ if(!den) return '—'; return ((num/den)*100).toFixed(1)+'%'; }

    function setTotals(t){
      document.getElementById('totalClicks').textContent  = 'کلیک: ' + (t.clicks||0).toLocaleString('en');
      document.getElementById('totalSeen').textContent    = 'دیده‌شدن: ' + (t.seen||0).toLocaleString('en');
      document.getElementById('totalGateway').textContent = 'درگاه: ' + (t.inGateway||0).toLocaleString('en');
      document.getElementById('totalPaid').textContent    = 'پرداخت: ' + (t.paid||0).toLocaleString('en');
    }

    function renderRows(data){
      const tbody = document.querySelector('#resultTable tbody');
      tbody.innerHTML = '';
      data.forEach(r=>{
        const label = (r.grp && r.grp.toLowerCase() === 'banner') ? 'banner' : r.grp;
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td><span class="badge bg-primary-subtle text-primary fw-bold">${label}</span></td>
          <td class="fw-semibold">${(r.clicks||0).toLocaleString('en')}</td>
          <td class="fw-semibold">${(r.seen||0).toLocaleString('en')}</td>
          <td class="fw-semibold">${(r.inGateway||0).toLocaleString('en')}</td>
          <td class="fw-semibold">${(r.paid||0).toLocaleString('en')}</td>
          <td class="small">
            <div class="d-flex flex-column">
              <span><i class="bi bi-eye"></i> Seen/Click: <strong>${fmtPercent(r.seen, r.clicks)}</strong></span>
              <span><i class="bi bi-credit-card"></i> Gateway/Seen: <strong>${fmtPercent(r.inGateway, r.seen)}</strong></span>
              <span><i class="bi bi-bag-check"></i> Pay/Gateway: <strong>${fmtPercent(r.paid, r.inGateway)}</strong></span>
            </div>
          </td>
        `;
        tbody.appendChild(tr);
      });
    }

    const form = document.getElementById('filterForm');
    form.addEventListener('submit', (e)=>{
      e.preventDefault();
      const btnSpin = document.getElementById('btnSpin');
      btnSpin.style.display='inline-block';

      const fd = new FormData(form);
      fd.append('asJson','1'); // API همین فایل

      axios.get(window.location.pathname + '?' + new URLSearchParams(fd).toString())
        .then(res=>{
          if(!res.data || !res.data.data){ alert('پاسخی دریافت نشد.'); return; }
          renderRows(res.data.data);
          setTotals(res.data.totals || {});
        })
        .catch(err=>{
          console.error(err);
          const msg = (err.response && err.response.data && err.response.data.error) ? err.response.data.error : 'خطا در دریافت داده‌ها';
          alert('❌ ' + msg);
        })
        .finally(()=>{ btnSpin.style.display='none'; });
    });

    // نمونه مقدار اولیه (اختیاری):
    // document.querySelector('input[name="from"]').value = '1403Y12M01D';
    // document.querySelector('input[name="to"]').value   = '1403Y12M29D';
  </script>
</body>
</html>
