<?php
// Handle report fetching
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['from']) && isset($_GET['to'])) {

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

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

    $from = $_GET["from"];
    $to = $_GET["to"];
    $R = $_GET["R"] ?? 'all';
    $type = $_GET["type"] ?? 'normal';

    $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 = shamsiToTs($yearFrom, $monthFrom, $dayFrom);
    $toTs = shamsiToTs($yearTo, $monthTo, $dayTo);

    $fromTs = currentTsToPaymentTs($fromTs);
    $toTs = currentTsToPaymentTs($toTs);

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

    $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;
    }

    $query = "SELECT * FROM `$tableName` WHERE `createdAt` > $fromTs AND `createdAt` < $toTs AND `type`!='direct' AND `type`!='tamdid' AND `type`!='new'";
    if ($R !== "all") {
        $query .= " AND `type` = '$R'";
    }

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

    $count = 0;
    $isSeen = 0;
    $isInGateway = 0;
    $isPay = 0;
    $payPhones = array();
    $gwPhones = array();
    $seenPhones = array();
    $allPhones = array();

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            array_push($allPhones, $row["phone"]);
            $count++;
            if ($row["isSeen"]) {$isSeen++; array_push($seenPhones, $row["phone"]); }
            if ($row["isInGateway"]) {$isInGateway++; array_push($gwPhones, $row["phone"]); }
            if ($row["isPay"]) {$isPay++; array_push($payPhones, $row["phone"]); }
        }
    }

    // Remove duplicates step by step
    $gwPhones = array_diff($gwPhones, $payPhones);
    $seenPhones = array_diff($seenPhones, $gwPhones);
    $allPhones = array_diff($allPhones, $seenPhones);

    // Return response
    echo json_encode([
        "all" => $count,
        "isSeen" => $isSeen,
        "isInGateway" => $isInGateway,
        "isPay" => $isPay,
        "phones" => [
            "all" => array_values($allPhones),
            "isSeen" => array_values($seenPhones),
            "isInGateway" => array_values($gwPhones),
            "isPay" => array_values($payPhones)
        ]
    ]);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Tamdid Report</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Bootstrap 5 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
      background-color: #f7f9fc;
    }
    .form-card {
      max-width: 700px;
      margin: auto;
    }
    .material-input:focus {
      box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
      border-color: #86b7fe;
    }
    .result-card {
      max-width: 700px;
      margin: 30px auto;
    }
  </style>
</head>
<body>
  <div class="container py-5">
    <h2 class="text-center mb-4">📊 Tamdid Report Dashboard</h2>

    <div class="card shadow-sm p-4 form-card">
      <form id="reportForm">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">From Date (e.g., 1403Y12M01D)</label>
            <input type="text" name="from" class="form-control material-input" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">To Date (e.g., 1403Y12M29D)</label>
            <input type="text" name="to" class="form-control material-input" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Type</label>
            <select name="type" class="form-select material-input">
              <option value="normal">Normal</option>
              <option value="drop">Drop</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">R Parameter</label>
            <input type="text" name="R" class="form-control material-input" placeholder="e.g. all or subscription">
          </div>
        </div>
        <button class="btn btn-primary w-100 mt-4" type="submit">Get Report</button>
      </form>
    </div>

    <div class="result-card d-none" id="resultCard">
      <div class="card shadow p-4">
        <h5 class="card-title text-center mb-3">📈 Results</h5>
        <ul class="list-group list-group-flush" id="resultList">
          <!-- Results will be injected here -->
        </ul>
      </div>
    </div>
  </div>

  <!-- Axios -->
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>

async function downloadPhones(phoneList) {
  const url = "https://admin.matchadiet.com/data/panel/users/export-by-phones";
  const authToken = "hbqdmzewP2osagSfx18traIaUOw8qXQqCMdJVwuOyiP4qCbgLSJaDmAE4Rjgko3t";

  // تبدیل ورودی به CSV دقیقاً به شکل "989...,989..."
  const phonesCsv = Array.isArray(phoneList)
    ? phoneList.map(p => String(p).trim()).join(",")
    : String(phoneList).trim();

  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      authToken,
      phones: phonesCsv   // ⟵ دقیقا رشته CSV، نه آرایه
    })
  });

  if (!res.ok) {
    const t = await res.text().catch(() => "");
    throw new Error(`HTTP ${res.status}: ${t}`);
  }

  // دانلود پاسخ به‌صورت فایل (CSV/Excel/...)
  const blob = await res.blob();
  let filename = "export.csv";
  const cd = res.headers.get("content-disposition");
  if (cd) {
    const m = cd.match(/filename\*?=(?:UTF-8''|")?([^";\n]+)/i);
    if (m && m[1]) filename = decodeURIComponent(m[1].replace(/"/g, ""));
  }
  const dl = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = dl;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(dl);
}


// مثال استفاده:
// downloadPhones("989370312141,989370312141");




  

    document.getElementById("reportForm").addEventListener("submit", function (e) {
      e.preventDefault();

      const formData = new FormData(this);
      const params = new URLSearchParams(formData).toString();

      axios.get(window.location.pathname + "?" + params)
        .then(res => {
          const data = res.data;
          const phones = data.phones;
          const resultList = document.getElementById("resultList");

            resultList.innerHTML = `
              <li class="list-group-item d-flex justify-content-between align-items-center">
                All: <strong>${data.all}</strong>
                <button class="btn btn-sm btn-outline-primary" onclick='downloadPhones(${JSON.stringify(phones.all)})'>Export</button>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                isSeen: <strong>${data.isSeen}</strong>
                <button class="btn btn-sm btn-outline-primary" onclick='downloadPhones(${JSON.stringify(phones.isSeen)})'>Export</button>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                isInGateway: <strong>${data.isInGateway}</strong>
                <button class="btn btn-sm btn-outline-primary" onclick='downloadPhones(${JSON.stringify(phones.isInGateway)})'>Export</button>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                isPay: <strong>${data.isPay}</strong>
                <button class="btn btn-sm btn-outline-primary" onclick='downloadPhones(${JSON.stringify(phones.isPay)})'>Export</button>
              </li>
            `;
          document.getElementById("resultCard").classList.remove("d-none");
        })
        .catch(err => {
          alert("❌ Error fetching report. Please check inputs.");
        });
    });
  </script>
</body>
</html>
