<?php
session_start();

/* ---------- DB CONFIG ---------- */
$config_paths = [
    '../includes/db_config.php',   // основний
    './includes/db_config.php',    // запасний
    '../includes/config.php',      // якщо є
];
$config_found = false;
foreach ($config_paths as $path) {
    if (is_file($path)) { include $path; $config_found = true; break; }
}
if (!$config_found) {
    die("Не вдалося знайти файл конфігурації (db_config.php).");
}

/* ---------- ACCESS ---------- */
$is_authorized = isset($_SESSION['user_id']) && in_array(($_SESSION['role'] ?? ''), ['admin','teacher'], true);
if (!$is_authorized) { header("Location: ../index.php"); exit; }

$group_id = isset($_GET['group_id']) ? (int)$_GET['group_id'] : 0;
if ($group_id <= 0) { header("Location: ../index.php"); exit; }

/* ---------- READ GROUP ---------- */
$sql = "SELECT name FROM `groups` WHERE id = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) { die("DB error: ".$conn->error); }
$stmt->bind_param("i", $group_id);
$stmt->execute();
$group = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$group) { header("Location: ../index.php"); exit; }

/* ---------- CONSTANTS ---------- */
$days_order = ['Пн','Вт','Ср','Чт','Пт']; // за потреби додай 'Сб'
$lessons_per_day = 8;     // сітка для відображення
$full_day_lessons = 6;    // «виробниче навчання» = 6 пар

/* ---------- LOAD TIME SLOTS ---------- */
$time_slots = [];
$sql = "SELECT lesson_number, start_time, end_time FROM lesson_times WHERE group_id = ? ORDER BY lesson_number";
$stmt = $conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("i", $group_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $start = substr((string)$row['start_time'],0,5);
        $end   = substr((string)$row['end_time'],0,5);
        $time_slots[(int)$row['lesson_number']] = "$start–$end";
    }
    $stmt->close();
}
if (empty($time_slots)) {
    $time_slots = [
        1 => '9:00–9:45', 2 => '9:55–10:40', 3 => '10:50–11:35', 4 => '11:55–12:40',
        5 => '12:50–13:35', 6 => '13:45–14:30', 7 => '14:40–15:25', 8 => '15:30–16:15',
    ];
}

/* ---------- HELPERS ---------- */
function norm_lines(string $s): array {
    $arr = preg_split("/\r\n|\n|\r/", $s);
    return $arr === false ? [] : $arr;
}
function split_cols(string $line): array {
    $cols = explode("\t", $line);
    if (count($cols) < 3) $cols = array_pad($cols, 3, '');
    if (count($cols) > 3) $cols = array_slice($cols, 0, 3);
    return [trim($cols[0]), trim($cols[1]), trim($cols[2])];
}
function is_blank(string $line): bool { return trim($line) === ''; }
function day_from_header(string $line): ?string {
    $t = mb_strtolower(trim($line), 'UTF-8');
    $t = preg_replace('/[:：]+$/u', '', $t);
    $map = [
        'пн'=>'Пн','понеділок'=>'Пн','понедiлок'=>'Пн',
        'вт'=>'Вт','вівторок'=>'Вт','вiвторок'=>'Вт',
        'ср'=>'Ср','середа'=>'Ср',
        'чт'=>'Чт','четвер'=>'Чт',
        'пт'=>'Пт','п’ятниця'=>'Пт','пятниця'=>'Пт','п\'ятниця'=>'Пт',
        // 'сб'=>'Сб','субота'=>'Сб',
    ];
    return $map[$t] ?? null;
}
function is_full_day_subject(?string $subject): bool {
    if ($subject === null) return false;
    return (bool)preg_match('/\bвиробнич/iu', $subject);
}
function val_or_null($s) {
    $s = trim((string)$s);
    return $s === '' ? null : $s;
}

/**
 * Парсер тижня: повертає [$parsed, $warnings]
 */
function parse_week_text(string $text, array $days_order, int $lessons_per_day, int $full_day_lessons): array {
    $lines = norm_lines($text);

    $parsed = []; foreach ($days_order as $d) { $parsed[$d] = []; }
    $warnings = [];

    $current_day = null;
    $day_index = 0;

    $has_any_marker = false;
    $has_blank_anywhere = false;
    foreach ($lines as $ln) {
        if (is_blank($ln)) { $has_blank_anywhere = true; }
        else { if (day_from_header($ln) !== null) $has_any_marker = true; }
    }
    if (!$has_any_marker && !$has_blank_anywhere) {
        $warnings[] = "Не виявлено заголовків днів або порожніх рядків як розділювачів. Усе піде в Пн. Додай заголовки або порожні рядки між днями.";
    }

    $prev_was_blank = false;
    $suppress_next_blank_advance = false;

    foreach ($lines as $line) {

        $dh = day_from_header($line);
        if ($dh !== null) {
            $current_day = $dh;
            $day_index = array_search($dh, $days_order, true);
            if ($day_index === false) $day_index = 0;
            $prev_was_blank = false;
            $suppress_next_blank_advance = false;
            continue;
        }

        if (is_blank($line)) {
            if ($prev_was_blank) continue;
            if ($suppress_next_blank_advance) {
                $prev_was_blank = true;
                $suppress_next_blank_advance = false;
                continue;
            }
            if ($current_day !== null) {
                if ($day_index + 1 < count($days_order)) {
                    $day_index++;
                    $current_day = $days_order[$day_index];
                } else {
                    $current_day = null;
                }
            } else {
                $current_day = $days_order[$day_index];
            }
            $prev_was_blank = true;
            continue;
        }

        $prev_was_blank = false;

        if ($current_day === null) {
            $current_day = $days_order[$day_index];
        }

        [$subj, $teach, $room] = split_cols($line);
        if ($subj === '' && $teach === '' && $room === '') continue;

        if (count($parsed[$current_day]) === 0 && is_full_day_subject($subj)) {
            for ($i=0; $i<$full_day_lessons; $i++) {
                $parsed[$current_day][] = [$subj, $teach, $room];
            }
            if ($day_index + 1 < count($days_order)) {
                $day_index++;
                $current_day = $days_order[$day_index];
            } else {
                $current_day = null;
            }
            $suppress_next_blank_advance = true;
            $prev_was_blank = false;
            continue;
        }

        if (count($parsed[$current_day]) < $lessons_per_day) {
            $parsed[$current_day][] = [$subj, $teach, $room];
        } else {
            $warnings[] = "День {$current_day} має більше {$lessons_per_day} записів — зайві обрізано.";
        }
    }

    foreach ($days_order as $d) {
        while (count($parsed[$d]) < $lessons_per_day) {
            $parsed[$d][] = ['', '', ''];
        }
    }

    return [$parsed, $warnings];
}

/* ---------- PREVIEW & SAVE ---------- */
$raw_text = '';
$parsed = null;
$warnings = [];
$info = [];

// Керування розсилкою: true = увімкнути
$ENABLE_IMPORT_EMAILS = true;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw_text = (string)($_POST['weekly_paste'] ?? '');
    $wipe = !empty($_POST['wipe_week']);

    [$parsed, $warnings] = parse_week_text($raw_text, $days_order, $lessons_per_day, $full_day_lessons);

    if (isset($_POST['preview'])) {
        // тільки прев’ю
    } elseif (isset($_POST['save'])) {

        if ($wipe) {
            $placeholders = implode(',', array_fill(0, count($days_order), '?'));
            $types = 'i' . str_repeat('s', count($days_order));
            $sql = "DELETE FROM schedules WHERE group_id = ? AND day_of_week IN ($placeholders)";
            $stmt = $conn->prepare($sql);
            if ($stmt) {
                $params = [$group_id];
                foreach ($days_order as $d) $params[] = $d;
                $stmt->bind_param($types, ...$params);
                $stmt->execute();
                $stmt->close();
                $info[] = "Тиждень очищено перед імпортом (Пн–Пт).";
            } else {
                $warnings[] = "Не вдалося очистити тиждень: ".$conn->error;
            }
        }

        $success = 0;
        foreach ($days_order as $d) {
            for ($lesson=1; $lesson<=$lessons_per_day; $lesson++) {
                $slot = $time_slots[$lesson] ?? null;
                if (!$slot) continue;

                $row  = $parsed[$d][$lesson-1] ?? ['', '', ''];
                $subj = val_or_null($row[0] ?? '');
                $teach= val_or_null($row[1] ?? '');
                $room = val_or_null($row[2] ?? '');

                if ($subj===null && $teach===null && $room===null) continue;

                $check_sql = "SELECT id FROM schedules WHERE group_id = ? AND day_of_week = ? AND time_slot = ? LIMIT 1";
                $check_stmt = $conn->prepare($check_sql);
                if (!$check_stmt) { $warnings[] = "DB error: ".$conn->error; continue; }
                $check_stmt->bind_param("iss", $group_id, $d, $slot);
                $check_stmt->execute();
                $existing = $check_stmt->get_result()->fetch_assoc();
                $check_stmt->close();

                if ($existing) {
                    $sid = (int)$existing['id'];
                    $sql = "UPDATE schedules SET subject=?, teacher=?, room=? WHERE id=?";
                    $stmt = $conn->prepare($sql);
                    if ($stmt) $stmt->bind_param("sssi", $subj, $teach, $room, $sid);
                } else {
                    $sql = "INSERT INTO schedules (group_id, day_of_week, time_slot, subject, teacher, room)
                            VALUES (?,?,?,?,?,?)";
                    $stmt = $conn->prepare($sql);
                    if ($stmt) $stmt->bind_param("isssss", $group_id, $d, $slot, $subj, $teach, $room);
                }

                if ($stmt && $stmt->execute()) { $success++; }
                if ($stmt) $stmt->close();
            }
        }

        /* ---------- EMAIL NOTIFY ---------- */
        if ($ENABLE_IMPORT_EMAILS && $success > 0) {
            $subs_sql = "SELECT email, verification_token FROM subscriptions WHERE group_id = ? AND is_verified = 1";
            $st = $conn->prepare($subs_sql);
            if ($st) {
                $st->bind_param("i", $group_id);
                $st->execute();
                $subs = $st->get_result();
            } else {
                $subs = false;
                error_log("weekly_import: cannot load subscriptions: ".$conn->error);
            }

            $sent_with_custom = false;
            $custom_file = __DIR__ . '/../send_schedule_updates.php';
            if (is_file($custom_file)) {
                include_once $custom_file;
                if (function_exists('sendSubscriptionEmail')) {
                    $sent_with_custom = true;
                    if ($subs) {
                        while ($sub = $subs->fetch_assoc()) {
                            try {
                                @sendSubscriptionEmail($sub['email'], $group['name'], $group_id, $sub['verification_token'], true);
                            } catch (Throwable $e) {
                                error_log("custom sendSubscriptionEmail failed for {$sub['email']}: ".$e->getMessage());
                            }
                        }
                        $st->free_result();
                        $st->execute();
                        $subs = $st->get_result();
                    }
                }
            }

            if (!$sent_with_custom) {
                $mail_cfg_file = __DIR__ . '/../includes/config_mail.php';
                $phpmailer_dir = __DIR__ . '/../includes/PHPMailer/src';
                if (is_file($mail_cfg_file) && is_dir($phpmailer_dir)) {
                    $config_mail = include $mail_cfg_file;
                    $ph1 = $phpmailer_dir . '/PHPMailer.php';
                    $ph2 = $phpmailer_dir . '/Exception.php';
                    $ph3 = $phpmailer_dir . '/SMTP.php';
                    if (is_file($ph1) && is_file($ph2) && is_file($ph3)) {
                        require_once $ph1; require_once $ph2; require_once $ph3;

                        $host = $config_mail['host']     ?? null;
                        $port = (int)($config_mail['port'] ?? 587);
                        $user = $config_mail['username'] ?? null;
                        $pass = $config_mail['password'] ?? null;
                        $secure = $config_mail['secure'] ?? 'tls';
                        $auth   = (bool)($config_mail['auth'] ?? true);
                        $from = $config_mail['from'] ?? 'no-reply@example.com';
                        $from_name = $config_mail['from_name'] ?? 'Розклад';

                        $subject = "Оновлено розклад групи «{$group['name']}»";
                        $scheduleUrl = "https://" . ($_SERVER['HTTP_HOST'] ?? 'localhost') . "/rozklad/group_schedule.php?id=" . urlencode((string)$group_id);

                        if ($subs) {
                            while ($sub = $subs->fetch_assoc()) {
                                try {
                                    $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
                                    $mail->isSMTP();
                                    $mail->Host = $host;
                                    $mail->Port = $port;
                                    $mail->SMTPAuth = $auth;
                                    $mail->SMTPSecure = $secure;
                                    if ($mail->SMTPAuth) { $mail->Username = $user; $mail->Password = $pass; }
                                    $mail->CharSet = 'UTF-8';
                                    $mail->setFrom($from, $from_name);
                                    $mail->addAddress($sub['email']);
                                    $mail->Subject = $subject;
                                    $body = "Вітаємо!\n\n"
                                          . "Розклад групи «{$group['name']}» було оновлено.\n"
                                          . "Переглянути: {$scheduleUrl}\n\n"
                                          . "Якщо ви не очікували цього листа — просто ігноруйте його.";
                                    $mail->Body = $body;
                                    $mail->AltBody = $body;
                                    $mail->send();
                                } catch (Throwable $e) {
                                    error_log("PHPMailer notify failed for {$sub['email']}: ".$e->getMessage());
                                }
                            }
                        }
                    } else {
                        error_log("weekly_import: PHPMailer files not found in includes/PHPMailer/src");
                    }
                } else {
                    if (!is_file($mail_cfg_file)) error_log("weekly_import: missing includes/config_mail.php");
                    if (!is_dir($phpmailer_dir))  error_log("weekly_import: missing includes/PHPMailer/src directory");
                }
            }

            if (!empty($st)) $st->close();
        } elseif ($ENABLE_IMPORT_EMAILS && $success == 0) {
            error_log("weekly_import: no schedule changes; emails suppressed");
        }

        header("Location: /admin/dashboard_schedule.php?group_id={$group_id}&import_success={$success}");
        exit;
    }
}

/* ---------- LOAD CURRENT SCHEDULE FOR PREVIEW ---------- */
$current = [];
$sql = "SELECT day_of_week, time_slot, subject, teacher, room FROM schedules WHERE group_id = ?";
$stmt = $conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("i", $group_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $lesson_no = null;
        foreach ($time_slots as $ln => $ts) {
            if ($ts === $row['time_slot']) { $lesson_no = $ln; break; }
        }
        if ($lesson_no !== null && in_array($row['day_of_week'], $days_order, true)) {
            $d = $row['day_of_week'];
            $current[$d][$lesson_no] = [
                'subject'=>(string)($row['subject']??''),
                'teacher'=>(string)($row['teacher']??''),
                'room'   =>(string)($row['room']??''),
            ];
        }
    }
    $stmt->close();
}

/* ----- закриємо конект (далі тільки рендер) ----- */
$conn->close();

/* ===== header.php vars ===== */
$siteName  = 'Розклад занять';
$pageTitle = 'Тижневий імпорт — ' . (string)($group['name'] ?? '');
$pageCss   = [
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
    '/css/admin.css?v=4',
    '/css/admin_weekly_import.css?v=1'
];

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

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

      <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
        <h1 class="admin-title mb-0">Тижневий імпорт — <?= htmlspecialchars((string)$group['name'], ENT_QUOTES, 'UTF-8'); ?></h1>
        <a class="btn btn-outline-secondary" href="/admin/dashboard_schedule.php?group_id=<?= (int)$group_id; ?>">← Повернутися</a>
      </div>

      <?php foreach ($info as $m): ?>
        <div class="alert alert-success"><?= htmlspecialchars((string)$m, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endforeach; ?>
      <?php foreach ($warnings as $w): ?>
        <div class="alert alert-warning"><?= htmlspecialchars((string)$w, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endforeach; ?>

      <div class="alert alert-info">
        Вставляй увесь тиждень одним блоком. Між днями став <strong>порожній рядок</strong> або додай <strong>заголовок дня</strong>
        (<span class="code">Пн</span>, <span class="code">Понеділок</span>, <span class="code">Вт</span>, <span class="code">Вівторок</span>, …).
        Формат: <strong>Предмет [TAB] Викладач [TAB] Кабінет</strong>.
        Якщо перший запис дня містить «виробнич» — заповнимо увесь день ним (<strong>6 уроків</strong>).
      </div>

      <form method="post" class="wi-grid">
        <section class="card-block">
          <div class="mb-2 form-check">
            <input class="form-check-input" type="checkbox" id="wipe_week" name="wipe_week" value="1">
            <label class="form-check-label" for="wipe_week">Очистити Пн–Пт перед імпортом</label>
          </div>

          <textarea
            name="weekly_paste"
            rows="18"
            class="form-control code"
            placeholder="Приклад:
Пн:
Біологія[TAB]Вишинська О.Л.[TAB]27

(порожній рядок)
Вт:
Інформатика[TAB]Мошнягул С.І.[TAB]37
..."
          ><?= htmlspecialchars((string)$raw_text, ENT_QUOTES, 'UTF-8'); ?></textarea>

          <div class="d-flex gap-2 mt-3 flex-wrap">
            <button type="submit" name="preview" class="btn btn-outline-primary wi-btn">Попередній перегляд</button>
            <button type="submit" name="save" class="btn btn-success wi-btn">Зберегти</button>
          </div>
        </section>

        <section class="card-block">
          <h2 class="block-title mb-2">Прев’ю імпорту</h2>

          <?php if ($parsed === null): ?>
            <div class="text-muted">Натисни «Попередній перегляд» щоб побачити розподіл по днях.</div>
          <?php else: ?>
            <?php foreach ($days_order as $d): ?>
              <div class="mb-3">
                <strong class="wi-day"><?= htmlspecialchars($d, ENT_QUOTES, 'UTF-8'); ?></strong>
                <div class="table-responsive wi-table">
                  <table class="table table-sm mini align-middle mb-0">
                    <thead>
                      <tr>
                        <th style="width:32px;">#</th>
                        <th style="width:120px;">Час</th>
                        <th>Предмет</th>
                        <th>Викладач</th>
                        <th style="width:90px;">Каб.</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php for ($i=1; $i<=$lessons_per_day; $i++):
                        $ts = $time_slots[$i] ?? '';
                        $row = $parsed[$d][$i-1] ?? ['', '', ''];
                      ?>
                      <tr>
                        <td><?= $i; ?></td>
                        <td><span class="badge slot-badge"><?= htmlspecialchars((string)$ts, ENT_QUOTES, 'UTF-8'); ?></span></td>
                        <td><?= htmlspecialchars((string)($row[0] ?? ''), ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?= htmlspecialchars((string)($row[1] ?? ''), ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?= htmlspecialchars((string)($row[2] ?? ''), ENT_QUOTES, 'UTF-8'); ?></td>
                      </tr>
                      <?php endfor; ?>
                    </tbody>
                  </table>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>

          <h2 class="block-title mb-2 mt-4">Поточний розклад (для порівняння)</h2>
          <?php foreach ($days_order as $d): ?>
            <div class="mb-3">
              <strong class="wi-day"><?= htmlspecialchars($d, ENT_QUOTES, 'UTF-8'); ?></strong>
              <div class="table-responsive wi-table">
                <table class="table table-sm mini align-middle mb-0">
                  <thead>
                    <tr>
                      <th style="width:32px;">#</th>
                      <th style="width:120px;">Час</th>
                      <th>Предмет</th>
                      <th>Викладач</th>
                      <th style="width:90px;">Каб.</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php for ($i=1; $i<=$lessons_per_day; $i++):
                      $ts = $time_slots[$i] ?? '';
                      $pref = $current[$d][$i] ?? ['subject'=>'','teacher'=>'','room'=>''];
                    ?>
                    <tr>
                      <td><?= $i; ?></td>
                      <td><span class="badge slot-badge"><?= htmlspecialchars((string)$ts, ENT_QUOTES, 'UTF-8'); ?></span></td>
                      <td><?= htmlspecialchars((string)$pref['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
                      <td><?= htmlspecialchars((string)$pref['teacher'], ENT_QUOTES, 'UTF-8'); ?></td>
                      <td><?= htmlspecialchars((string)$pref['room'], ENT_QUOTES, 'UTF-8'); ?></td>
                    </tr>
                    <?php endfor; ?>
                  </tbody>
                </table>
              </div>
            </div>
          <?php endforeach; ?>
        </section>
      </form>

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

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
