<?php
// /admin/pdf_archives.php
session_start();
require_once __DIR__ . '/../includes/db_config.php';
date_default_timezone_set('Europe/Kyiv');

$role = strtolower(trim($_SESSION['role'] ?? ''));
if (!isset($_SESSION['user_id']) || !in_array($role, ['admin','teacher'], true)) {
    header("Location: ../login.php");
    exit;
}

function adminActiveTab(string $file): string {
    $self = basename($_SERVER['PHP_SELF']);
    return $self === $file ? ' class="nav-link active"' : ' class="nav-link"';
}

/* ===== Список груп ===== */
$groups = [];
if ($res = $conn->query("SELECT id, name FROM `groups` ORDER BY position, name")) {
    while ($row = $res->fetch_assoc()) $groups[] = $row;
    $res->free();
}

/* ===== Початок тижня (понеділок) ===== */
function mondayOf(?string $dateYmd = null): string {
    $dt = new DateTime($dateYmd ?: 'today');
    $dow = (int)$dt->format('N'); // 1..7
    if ($dow !== 1) $dt->modify('-' . ($dow - 1) . ' days');
    return $dt->format('Y-m-d');
}

$results = [];
$week_start = (string)($_POST['week_start'] ?? mondayOf());

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selected = array_map('intval', (array)($_POST['group_ids'] ?? []));
    $mode = (string)($_POST['mode'] ?? '');

    if ($mode === 'all') $selected = array_map('intval', array_column($groups, 'id'));

    if (empty($selected)) {
        $results[] = ['group_id'=>null, 'status'=>'error', 'message'=>'Не вибрано жодної групи.', 'url'=>''];
    } else {
        $host = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https://' : 'http://') . ($_SERVER['HTTP_HOST'] ?? 'localhost');

        foreach ($selected as $gid) {
            $url = $host . "/scripts/pdf/generate_group_pdf.php?group_id={$gid}&week_start={$week_start}";
            $ok = false; $msg = ''; $savedUrl = '';

            // 1) cURL
            if (function_exists('curl_init')) {
                $ch = curl_init($url);
                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_CONNECTTIMEOUT => 10,
                    CURLOPT_TIMEOUT => 120,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_SSL_VERIFYHOST => false,
                ]);
                $response = curl_exec($ch);
                $err = curl_error($ch);
                $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);

                if ($code === 200 && $response) {
                    $json = json_decode($response, true);
                    if (is_array($json) && ($json['status'] ?? '') === 'ok') {
                        $ok = true;
                        $savedUrl = (string)($json['url'] ?? '');
                        $msg = 'OK (generated)';
                    } else {
                        $msg = 'Bad JSON/Status';
                    }
                } else {
                    $msg = $err ? ("cURL: ".$err) : "HTTP {$code}";
                }
            }

            // 2) fopen
            if (!$ok && ini_get('allow_url_fopen')) {
                $context = stream_context_create(['http'=>['timeout'=>120, 'follow_location'=>1]]);
                $response = @file_get_contents($url, false, $context);
                if ($response) {
                    $json = json_decode($response, true);
                    if (is_array($json) && ($json['status'] ?? '') === 'ok') {
                        $ok = true;
                        $savedUrl = (string)($json['url'] ?? '');
                        $msg = 'OK (generated)';
                    } else {
                        $msg = 'Bad JSON/Status';
                    }
                } else {
                    $msg = 'fopen fail';
                }
            }

            $results[] = [
                'group_id' => $gid,
                'status'   => $ok ? 'success' : 'error',
                'message'  => $msg ?: 'Помилка під час генерації',
                'url'      => $savedUrl
            ];
        }
    }
}

$conn->close();

/* ===== header.php vars ===== */
$siteName  = 'Розклад занять';
$pageTitle = 'PDF-архіви';
$pageCss   = [
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
    '/css/admin.css?v=4',
    '/css/admin_pdf_archives.css?v=1'
];

include __DIR__ . '/../includes/header.php';
?>

<main class="page">
  <div class="kp-container">
    <div class="container my-3 admin-wrap">

      <!-- Уніфіковані вкладки -->
      <ul class="nav nav-tabs mb-4 admin-tabs">
        <li class="nav-item"><a<?=adminActiveTab('dashboard.php')?> href="dashboard.php">Головна</a></li>
        <li class="nav-item"><a<?=adminActiveTab('teachers.php')?> href="teachers.php">Викладачі</a></li>
        <li class="nav-item"><a<?=adminActiveTab('dashboard_consultations.php')?> href="dashboard_consultations.php">Консультації</a></li>
        <li class="nav-item"><a<?=adminActiveTab('pdf_archives.php')?> href="pdf_archives.php">PDF-архіви</a></li>
      </ul>

      <h1 class="admin-title mb-2">Генерація PDF-архівів</h1>
      <p class="text-muted mb-3">
        Згенеруй архіви для позначених груп або одразу для всіх. Статус «OK» зʼявиться лише якщо файл реально створено.
      </p>

      <section class="card-block">
        <form method="post" id="massForm">
          <div class="row g-3 align-items-end">
            <div class="col-12 col-md-4">
              <label for="week_start" class="form-label">Тиждень від (понеділок)</label>
              <input type="date" id="week_start" name="week_start" value="<?= htmlspecialchars((string)$week_start, ENT_QUOTES, 'UTF-8') ?>" class="form-control">
            </div>

            <div class="col-12 col-md-8 d-flex gap-2 flex-wrap justify-content-md-end">
              <button type="submit" name="mode" value="selected" class="btn btn-primary admin-w-btn">Згенерувати для позначених</button>
              <button type="submit" name="mode" value="all" class="btn btn-outline-secondary admin-w-btn">Згенерувати для всіх груп</button>
            </div>
          </div>

          <div class="mt-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
            <strong>Групи</strong>
            <label class="text-muted" style="user-select:none; cursor:pointer;">
              <input type="checkbox" id="selectAll" style="vertical-align:middle;"> Позначити всі
            </label>
          </div>

          <div class="groups-list mt-2">
            <?php foreach ($groups as $g): ?>
              <label class="group-row">
                <input type="checkbox" name="group_ids[]" value="<?= (int)$g['id'] ?>" class="gid">
                <span class="g-name"><?= htmlspecialchars((string)$g['name'], ENT_QUOTES, 'UTF-8') ?></span>
                <span class="g-id">ID: <?= (int)$g['id'] ?></span>
              </label>
            <?php endforeach; ?>
          </div>

          <p class="text-muted mt-3 mb-0">
            Генерація виконується по черзі. Якщо файл не записано — у звіті буде «Помилка».
          </p>
        </form>
      </section>

      <?php if (!empty($results)): ?>
        <section class="card-block mt-3">
          <h2 class="block-title mb-3">Звіт</h2>

          <div class="table-responsive">
            <table class="table align-middle admin-table mb-0">
              <thead>
                <tr>
                  <th style="width:40%;">Група</th>
                  <th style="width:12%;">Статус</th>
                  <th style="width:33%;">Повідомлення</th>
                  <th style="width:15%;">Посилання</th>
                </tr>
              </thead>
              <tbody>
              <?php
                $map = [];
                foreach ($groups as $g) $map[(int)$g['id']] = (string)$g['name'];
                foreach ($results as $r):
                  $gid = $r['group_id'] ? (int)$r['group_id'] : 0;
                  $name = $gid ? ($map[$gid] ?? ('ID '.$gid)) : '—';

                  $ok = (($r['status'] ?? '') === 'success');
              ?>
                <tr>
                  <td><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></td>
                  <td>
                    <?= $ok
                      ? '<span class="badge bg-success-subtle text-success-emphasis border border-success-subtle">OK</span>'
                      : '<span class="badge bg-danger-subtle text-danger-emphasis border border-danger-subtle">Помилка</span>' ?>
                  </td>
                  <td class="text-break"><?= htmlspecialchars((string)($r['message'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                  <td>
                    <?php if (!empty($r['url'])): ?>
                      <a href="<?= htmlspecialchars((string)$r['url'], ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener">Відкрити</a>
                    <?php else: ?>
                      —
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </section>
      <?php endif; ?>

    </div>
  </div>
</main>

<script>
  const selectAll = document.getElementById('selectAll');
  const boxes = Array.from(document.querySelectorAll('.gid'));
  if (selectAll) {
    selectAll.addEventListener('change', () => {
      boxes.forEach(b => { b.checked = selectAll.checked; });
    });
  }
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>

</body>
</html>
