<?php
// /scripts/pdf/generate_group_pdf.php
declare(strict_types=1);

session_start();
date_default_timezone_set('Europe/Kyiv');

require_once __DIR__ . '/../../includes/db_config.php';

// ---- Вхідні параметри ----
$group_id   = isset($_GET['group_id']) ? (int)$_GET['group_id'] : 0;
$archive_date = $_GET['week_start'] ?? date('Y-m-d'); // дата в назві файлу (як у старому варіанті)

if ($group_id <= 0) {
    http_response_code(400);
    echo "ERR: invalid group_id";
    exit;
}

// ---- Назва групи ----
$stmt = $conn->prepare("SELECT name FROM `groups` WHERE id = ?");
$stmt->bind_param("i", $group_id);
$stmt->execute();
$res = $stmt->get_result();
$group = $res ? $res->fetch_assoc() : null;
$stmt->close();

if (!$group) {
    http_response_code(404);
    echo "ERR: group not found";
    exit;
}
$group_name = $group['name'] ?? ("Group {$group_id}");

// ---- Поточний розклад з таблиці schedules (як "було до оновлення") ----
$stmt = $conn->prepare("
    SELECT day_of_week, time_slot, subject, teacher, room, replacement, lesson_link, teacher_comment
    FROM `schedules`
    WHERE group_id = ?
    ORDER BY
      CASE day_of_week
        WHEN 'Пн' THEN 1 WHEN 'Вт' THEN 2 WHEN 'Ср' THEN 3
        WHEN 'Чт' THEN 4 WHEN 'Пт' THEN 5 WHEN 'Сб' THEN 6 WHEN 'Нд' THEN 7
        ELSE 99
      END,
      id
");
$stmt->bind_param("i", $group_id);
$stmt->execute();
$q = $stmt->get_result();
$rows = [];
while ($r = $q->fetch_assoc()) $rows[] = $r;
$stmt->close();

$conn->close();

// ---- Групування по днях ----
$days_order = ['Пн','Вт','Ср','Чт','Пт','Сб','Нд'];
$grouped = [];
foreach ($days_order as $d) $grouped[$d] = [];
foreach ($rows as $r) {
    $d = $r['day_of_week'] ?? '';
    if (!isset($grouped[$d])) $grouped[$d] = [];
    $grouped[$d][] = $r;
}

// ---- HTML-шаблон (як у «Має бути так») ----
$title = htmlspecialchars("Розклад — {$group_name} — {$archive_date}", ENT_QUOTES, 'UTF-8');

ob_start();
?>
<!DOCTYPE html>
<html lang="uk">
<head>
  <meta charset="UTF-8">
  <style>
    body { font-family: DejaVu Sans, sans-serif; font-size: 12px; margin: 16px; }
    h1 { font-size: 18px; margin: 0 0 8px 0; }
    .muted { color: #666; font-size: 11px; margin-bottom: 8px; }
    h3 { font-size: 14px; margin: 14px 0 6px; }
    table { border-collapse: collapse; width: 100%; }
    th, td { border: 1px solid #999; padding: 6px; vertical-align: top; }
    th { background: #f0f0f0; }
    .room { white-space: nowrap; }
    .wrap { word-break: break-word; }
  </style>
</head>
<body>
  <h1><?= $title ?></h1>
  <div class="muted">Згенеровано автоматично. Дата файлу: <?= htmlspecialchars($archive_date) ?></div>

  <?php foreach ($days_order as $day): ?>
    <?php if (!empty($grouped[$day])): ?>
      <h3><?= htmlspecialchars($day) ?></h3>
      <table>
        <thead>
          <tr>
            <th style="width:18%">Час</th>
            <th style="width:32%">Предмет</th>
            <th style="width:25%">Викладач</th>
            <th style="width:10%">Ауд.</th>
            <th style="width:15%">Примітка</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($grouped[$day] as $r): ?>
          <tr>
            <td class="room"><?= htmlspecialchars($r['time_slot'] ?? '') ?></td>
            <td class="wrap"><?= htmlspecialchars($r['subject'] ?? '') ?></td>
            <td class="wrap"><?= htmlspecialchars($r['teacher'] ?? '') ?></td>
            <td class="room"><?= htmlspecialchars($r['room'] ?? '') ?></td>
            <td class="wrap">
              <?php
                $note = '';
                if (!empty($r['replacement']))      $note .= 'Заміна: ' . $r['replacement'] . ' ';
                if (!empty($r['teacher_comment']))  $note .= $r['teacher_comment'] . ' ';
                echo htmlspecialchars(trim($note));
              ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  <?php endforeach; ?>
</body>
</html>
<?php
$html = ob_get_clean();

// ---- Рендер у PDF через Dompdf ----
$autoload = __DIR__ . '/../../includes/dompdf/autoload.inc.php';
if (!is_file($autoload)) {
    error_log("PDF: Dompdf autoload not found: {$autoload}");
    http_response_code(500);
    echo "ERR: dompdf missing";
    exit;
}

require_once $autoload;

try {
    $options = new Dompdf\Options();
    $options->set('isRemoteEnabled', true);
    $options->set('defaultFont', 'DejaVu Sans');

    $dompdf = new Dompdf\Dompdf($options);
    $dompdf->loadHtml($html, 'UTF-8');
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    // ---- Шлях збереження: /arhive/<Назва групи>/<Назва групи> <YYYY-MM-DD>.pdf ----
    $siteRoot  = realpath(__DIR__ . '/../../');
    $safeGroup = preg_replace('~[\\\\/:*?"<>|]+~u', ' ', $group_name);
    $targetDir = $siteRoot . '/arhive/' . $safeGroup;
    if (!is_dir($targetDir)) @mkdir($targetDir, 0777, true);

    if (!is_dir($targetDir)) {
        error_log("PDF: cannot create dir {$targetDir}");
        http_response_code(500);
        echo "ERR: cannot create target dir";
        exit;
    }

    $fileName  = $safeGroup . ' ' . $archive_date . '.pdf';
    $target    = $targetDir . '/' . $fileName;

    $pdfOutput = $dompdf->output();
    if (@file_put_contents($target, $pdfOutput) === false) {
        error_log("PDF: cannot write file {$target}");
        http_response_code(500);
        echo "ERR: cannot write file";
        exit;
    }

    // ---- OK + JSON ----
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https://' : 'http://';
    $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $url    = "{$scheme}{$host}/arhive/" . rawurlencode($safeGroup) . '/' . rawurlencode($fileName);

    http_response_code(200);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'status'     => 'ok',
        'group_id'   => $group_id,
        'group_name' => $group_name,
        'date'       => $archive_date,
        'path'       => str_replace($siteRoot, '', $target),
        'url'        => $url,
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    error_log("PDF Dompdf error: " . $e->getMessage());
    http_response_code(500);
    echo "ERR: dompdf error";
    exit;
}