<?php
declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/../lib/db.php';
require_once __DIR__ . '/../lib/helpers.php';
require_once __DIR__ . '/../lib/consent.php';
require_once __DIR__ . '/../lib/iys.php';
require_once __DIR__ . '/../lib/mail_settings.php';
require_once __DIR__ . '/../lib/smtp_mailer.php';

start_app_session();
if (empty($_SESSION['user_id'])) {
  header('Location: login.php');
  exit;
}

$pdo = db();
$mailCfg = mail_load_config($pdo, app_config());
$iysCfg = iys_load_config();

$defaultFrom = date('Y-m-d') . 'T00:00';
$defaultTo = date('Y-m-d') . 'T' . date('H:i');

$dateFrom = (string)($_POST['date_from'] ?? $_GET['date_from'] ?? $defaultFrom);
$dateTo = (string)($_POST['date_to'] ?? $_GET['date_to'] ?? $defaultTo);
$consentSource = 'HS_CAGRI_MERKEZI';
$bayiNo = trim((string)($iysCfg['brand_code'] ?? ''));
$izinTuru = 'MESAJ';
$toEmailsInput = trim((string)($_POST['to_emails'] ?? implode(', ', is_array($mailCfg['to'] ?? null) ? $mailCfg['to'] : [])));

$action = (string)($_POST['action'] ?? '');
$errors = [];
$success = '';
$rowCount = 0;

if ($action !== '') {
  csrf_verify();

  $fromTs = parse_report_datetime($dateFrom);
  $toTs = parse_report_datetime($dateTo);

  if ($fromTs <= 0) $errors[] = 'Baslangic tarihi gecersiz.';
  if ($toTs <= 0) $errors[] = 'Bitis tarihi gecersiz.';
  if ($fromTs > 0 && $toTs > 0 && $fromTs > $toTs) $errors[] = 'Baslangic tarihi bitisten buyuk olamaz.';
  if ($consentSource === '') $errors[] = 'Izin kaynagi bos olamaz.';
  if ($izinTuru === '') $errors[] = 'Izin turu bos olamaz.';
  if ($bayiNo === '') $errors[] = 'IYS bayi no (brandcode) bos. config/sms.php iys.brand_code alanini kontrol edin.';

  if (!$errors) {
    $fromSql = date('Y-m-d H:i:s', $fromTs);
    $toSql = date('Y-m-d H:i:s', $toTs);

    $rows = collect_consent_rows($pdo, $fromSql, $toSql, $izinTuru, $consentSource, $bayiNo);
    $rowCount = count($rows);

    if ($action === 'download_csv') {
      export_csv($rows, 'izin_log_' . date('Ymd_His') . '.csv');
      exit;
    }

    if ($action === 'send_mail') {
      $toList = parse_to_list($toEmailsInput);
      if (!$toList) {
        $errors[] = 'Mail alici listesi bos.';
      } elseif (!$rows) {
        $errors[] = 'Secilen tarih araliginda uygun log kaydi bulunamadi.';
      } else {
        $csv = csv_string($rows);
        $subject = 'Izin Log Raporu - ' . date('Y-m-d H:i');
        $body = implode("\n", [
          'Izin log raporu ektedir.',
          'Tarih araligi: ' . $fromSql . ' - ' . $toSql,
          'Toplam satir: ' . count($rows),
        ]);

        $fromEmail = trim((string)($mailCfg['from_email'] ?? ''));
        if ($fromEmail === '') {
          $fromEmail = 'ivr@wanyweb.com';
        }

        $mail = [
          'from_email' => $fromEmail,
          'from_name' => (string)($mailCfg['from_name'] ?? 'Wany IVR'),
          'to' => $toList,
          'subject' => $subject,
          'body' => $body,
          'attachments' => [[
            'name' => 'izin_log_' . date('Ymd_His') . '.csv',
            'mime' => 'text/csv',
            'content' => $csv,
          ]],
        ];

        try {
          $raw = mail_build_message($mail);
          smtp_send($mailCfg, [
            'from_email' => $mail['from_email'],
            'to' => $mail['to'],
            'raw' => $raw,
          ]);
          $success = 'Mail gonderildi. Alici: ' . implode(', ', $toList);
        } catch (Throwable $e) {
          $errors[] = 'Mail gonderilemedi: ' . $e->getMessage();
        }
      }
    }
  }
}

function parse_report_datetime(string $s): int
{
  $s = trim($s);
  if ($s === '') return 0;
  $ts = strtotime($s);
  return $ts === false ? 0 : (int)$ts;
}

function parse_to_list(string $raw): array
{
  $parts = preg_split('/[,\n;]+/', $raw) ?: [];
  $out = [];
  foreach ($parts as $p) {
    $p = trim($p);
    if ($p === '') continue;
    $out[] = $p;
  }
  return array_values(array_unique($out));
}

function collect_consent_rows(PDO $pdo, string $fromSql, string $toSql, string $izinTuru, string $consentSource, string $bayiNo): array
{
  $st = $pdo->prepare("
    SELECT id, created_at, raw_body
    FROM webhook_logs
    WHERE raw_body IS NOT NULL
      AND raw_body <> ''
      AND created_at BETWEEN ? AND ?
    ORDER BY created_at ASC, id ASC
  ");
  $st->execute([$fromSql, $toSql]);
  $rows = $st->fetchAll() ?: [];

  $out = [];
  foreach ($rows as $r) {
    $payload = parse_webhook_payload((string)($r['raw_body'] ?? ''));
    if (!$payload) continue;

    $tus = payload_pick($payload, ['tus_bilgisi', 'digit']);
    if ($tus === '') continue;

    $onayRet = '';
    if (consent_is_approved_digit($tus)) {
      $onayRet = '1';
    } elseif (consent_is_rejected_digit($tus)) {
      $onayRet = '0';
    } else {
      continue;
    }

    $aliciRaw = payload_pick($payload, ['arayan_no', 'arayan', 'caller', 'from', 'msisdn']);
    if ($aliciRaw === '') continue;
    $alici = normalize_csv_phone($aliciRaw);
    if ($alici === '') continue;

    $createdAt = (string)($r['created_at'] ?? '');
    $izinTarihi = format_izin_date($createdAt);

    $out[] = [
      $izinTuru,
      $alici,
      $onayRet,
      $consentSource,
      $izinTarihi,
      $bayiNo,
    ];
  }

  return $out;
}

function normalize_csv_phone(string $raw): string
{
  $digits = preg_replace('/\D+/', '', $raw) ?? '';
  if ($digits === '') return '';
  if (strlen($digits) === 12 && str_starts_with($digits, '90')) {
    return substr($digits, 2);
  }
  if (strlen($digits) === 11 && str_starts_with($digits, '0')) {
    return substr($digits, 1);
  }
  return $digits;
}

function format_izin_date(string $dt): string
{
  $ts = strtotime($dt);
  if ($ts === false) return $dt;
  return date('d-m-Y H:i:s', $ts);
}

function csv_string(array $rows): string
{
  $fp = fopen('php://temp', 'w+');
  fputcsv($fp, [
    'IZIN TURU',
    'ALICI',
    'ONAY(1)-RET(0)',
    'IZIN KAYNAGI',
    'IZIN TARIHI',
    'IZNIN ALINDIGI BAYI IYS NO',
  ], ',');

  foreach ($rows as $row) {
    fputcsv($fp, $row, ',');
  }

  rewind($fp);
  $csv = (string)stream_get_contents($fp);
  fclose($fp);
  return "\xEF\xBB\xBF" . $csv;
}

function export_csv(array $rows, string $fileName): void
{
  header('Content-Type: text/csv; charset=UTF-8');
  header('Content-Disposition: attachment; filename="' . $fileName . '"');
  echo csv_string($rows);
}
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>CSV Log Raporu</title>
  <style>
    @font-face {
      font-family: 'Nexa';
      src: url('/assets/fonts/NexaRegular.woff2') format('woff2'),
           url('/assets/fonts/NexaRegular.woff') format('woff');
      font-weight: 400;
      font-style: normal;
      font-display: swap;
    }
    @font-face {
      font-family: 'Nexa';
      src: url('/assets/fonts/Nexa Bold.woff2') format('woff2'),
           url('/assets/fonts/Nexa Bold.woff') format('woff');
      font-weight: 700;
      font-style: normal;
      font-display: swap;
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Nexa', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #fff;
      color: #111;
      padding: 10px;
    }
    .wrap { max-width: 860px; margin: 0 auto; }
    .head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      margin-bottom: 12px;
      flex-wrap: wrap;
    }
    .title { font-size: 20px; font-weight: 800; }
    .pill {
      background: #f1f1f1;
      border: 0;
      border-radius: 999px;
      padding: 8px 12px;
      text-decoration: none;
      color: #111;
      font-weight: 700;
      font-size: 13px;
    }
    .card {
      background: #f8f8f8;
      border-radius: 14px;
      padding: 12px;
      border: 1px solid #ececec;
    }
    .grid {
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 10px;
    }
    .field { display: flex; flex-direction: column; gap: 6px; }
    .field.full { grid-column: 1 / -1; }
    label { font-size: 12px; color: #666; font-weight: 700; }
    input, textarea {
      width: 100%;
      border: 1px solid #ddd;
      background: #fff;
      border-radius: 10px;
      padding: 10px;
      font-family: inherit;
      font-size: 14px;
    }
    textarea { min-height: 64px; resize: vertical; }
    .actions {
      margin-top: 12px;
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }
    .btn {
      border: 0;
      border-radius: 10px;
      padding: 10px 14px;
      font-weight: 800;
      cursor: pointer;
      font-family: inherit;
      font-size: 14px;
    }
    .btn.primary { background: #111; color: #fff; }
    .btn.green { background: #e8f5e9; color: #2e7d32; }
    .msg { margin-top: 10px; font-size: 13px; font-weight: 700; }
    .msg.ok { color: #2e7d32; }
    .msg.err { color: #c62828; }
    .meta { margin-top: 10px; font-size: 13px; color: #666; font-weight: 700; }
    @media (max-width: 640px) {
      .grid { grid-template-columns: 1fr; }
      .field.full { grid-column: auto; }
    }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="head">
      <div class="title">CSV Log Raporu</div>
      <a class="pill" href="dashboard.php">&larr; Panel</a>
    </div>

    <form class="card" method="post">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <div class="grid">
        <div class="field">
          <label>Baslangic Tarihi</label>
          <input type="datetime-local" name="date_from" value="<?= e($dateFrom) ?>">
        </div>
        <div class="field">
          <label>Bitis Tarihi</label>
          <input type="datetime-local" name="date_to" value="<?= e($dateTo) ?>">
        </div>
        <div class="field">
          <label>Izin Turu</label>
          <input type="text" name="izin_turu" value="<?= e($izinTuru) ?>" readonly>
        </div>
        <div class="field">
          <label>Izin Kaynagi</label>
          <input type="text" name="consent_source" value="<?= e($consentSource) ?>" readonly>
        </div>
        <div class="field">
          <label>IYS Bayi No (brandcode)</label>
          <input type="text" name="bayi_iys_no" value="<?= e($bayiNo) ?>" readonly>
        </div>
        <div class="field full">
          <label>Mail Alicilari (virgul, noktali virgul veya yeni satir)</label>
          <textarea name="to_emails" placeholder="mail1@ornek.com, mail2@ornek.com"><?= e($toEmailsInput) ?></textarea>
        </div>
      </div>

      <div class="actions">
        <button class="btn primary" type="submit" name="action" value="download_csv">CSV Indir</button>
        <button class="btn green" type="submit" name="action" value="send_mail">CSV Mail Gonder</button>
      </div>

      <?php if ($success !== ''): ?>
        <div class="msg ok"><?= e($success) ?></div>
      <?php endif; ?>
      <?php foreach ($errors as $er): ?>
        <div class="msg err"><?= e($er) ?></div>
      <?php endforeach; ?>
      <?php if ($rowCount > 0): ?>
        <div class="meta">Hazirlanan satir: <?= (int)$rowCount ?></div>
      <?php endif; ?>
    </form>
  </div>
</body>
</html>
