<?php
session_start();

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

/* ===== доступ ===== */
$role = strtolower(trim($_SESSION['role'] ?? ''));
$is_authorized = isset($_SESSION['user_id']) && in_array($role, ['admin','teacher'], true);

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

/* ===== дні тижня + вибір дня ===== */
$days_of_week_full = ['Пн','Вт','Ср','Чт','Пт','Сб'];

$selected_day = trim((string)($_GET['day'] ?? ''));
$selected_day_index = (int)($_GET['day_index'] ?? 0);

if ($selected_day === '' && $selected_day_index >= 1 && $selected_day_index <= 6) {
    $selected_day = $days_of_week_full[$selected_day_index - 1];
}
if ($selected_day !== '' && !in_array($selected_day, $days_of_week_full, true)) {
    $selected_day = '';
}
$selected_day_idx = 0;
if ($selected_day !== '') {
    $tmpIdx = array_search($selected_day, $days_of_week_full, true);
    $selected_day_idx = ($tmpIdx === false) ? 0 : ((int)$tmpIdx + 1);
}

/* ===== helpers ===== */
function val_or_null($s) {
    $s = trim((string)$s);
    return $s === '' ? null : $s;
}

function column_exists_mysqli(mysqli $conn, string $table, string $column): bool {
    $sql = "
        SELECT COUNT(*) AS c
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
        LIMIT 1
    ";
    $st = $conn->prepare($sql);
    if (!$st) return false;
    $st->bind_param("ss", $table, $column);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();
    return !empty($row) && (int)$row['c'] > 0;
}

function safe_upload_dir(string $absPath): bool {
    if (is_dir($absPath)) return true;
    return @mkdir($absPath, 0755, true);
}

function handle_upload_one(array $file, string $uploadAbsDir, string $uploadWebDir, array $allowedExt, int $maxBytes): array {
    if (empty($file) || !isset($file['error'])) {
        return ['ok' => true, 'path' => null, 'error' => null];
    }
    if ((int)$file['error'] === UPLOAD_ERR_NO_FILE) {
        return ['ok' => true, 'path' => null, 'error' => null];
    }
    if ((int)$file['error'] !== UPLOAD_ERR_OK) {
        return ['ok' => false, 'path' => null, 'error' => 'Помилка завантаження файлу (код: ' . (int)$file['error'] . ').'];
    }
    $size = (int)($file['size'] ?? 0);
    if ($size <= 0) return ['ok' => false, 'path' => null, 'error' => 'Файл порожній.'];
    if ($size > $maxBytes) return ['ok' => false, 'path' => null, 'error' => 'Файл завеликий. Максимум 25 МБ.'];

    $origName = (string)($file['name'] ?? '');
    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    if ($ext === '' || !in_array($ext, $allowedExt, true)) {
        return ['ok' => false, 'path' => null, 'error' => 'Недозволений тип файлу.'];
    }

    if (!safe_upload_dir($uploadAbsDir)) {
        return ['ok' => false, 'path' => null, 'error' => 'Не вдалося створити папку /upload/.'];
    }

    $safeBase = preg_replace('~[^a-zA-Z0-9_\-]+~', '_', pathinfo($origName, PATHINFO_FILENAME));
    $safeBase = trim((string)$safeBase, '_');
    if ($safeBase === '') $safeBase = 'file';

    $uniq = bin2hex(random_bytes(6));
    $newName = $safeBase . '_' . date('Ymd_His') . '_' . $uniq . '.' . $ext;
    $destAbs = rtrim($uploadAbsDir, '/\\') . DIRECTORY_SEPARATOR . $newName;
    $destWeb = rtrim($uploadWebDir, '/\\') . '/' . $newName;

    if (!@move_uploaded_file((string)($file['tmp_name'] ?? ''), $destAbs)) {
        return ['ok' => false, 'path' => null, 'error' => 'Не вдалося зберегти файл на сервері.'];
    }

    return ['ok' => true, 'path' => $destWeb, 'error' => null];
}

function build_return_url(int $group_id, string $day = '', array $params = [], string $anchor = ''): string {
    $url = "dashboard_schedule.php?group_id=" . (int)$group_id;
    if ($day !== '') $url .= "&day=" . urlencode($day);
    foreach ($params as $k => $v) {
        $url .= "&" . urlencode((string)$k) . "=" . urlencode((string)$v);
    }
    if ($anchor !== '') $url .= "#" . $anchor;
    return $url;
}

/* ===== група ===== */
$sql = "SELECT name FROM `groups` WHERE id = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Помилка підготовки запиту (groups): " . htmlspecialchars((string)$conn->error, ENT_QUOTES, 'UTF-8'));
}
$stmt->bind_param("i", $group_id);
$stmt->execute();
$group = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$group) {
    header("Location: ../index.php");
    exit;
}

/* ===== часові слоти ===== */
$time_slots = [];
$sql = "SELECT lesson_number, start_time, end_time FROM lesson_times WHERE group_id = ? ORDER BY lesson_number";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $group_id);
$stmt->execute();
$res = $stmt->get_result();
while ($slot = $res->fetch_assoc()) {
    $start = substr((string)$slot['start_time'], 0, 5);
    $end   = substr((string)$slot['end_time'], 0, 5);
    $time_slots[(int)$slot['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'
    ];
}

/* ===== колонка attachment_path ===== */
$has_attachment_path = column_exists_mysqli($conn, 'schedules', 'attachment_path');

/* ===== upload settings ===== */
$uploadWebDir = '/upload';
$uploadAbsDir = realpath(__DIR__ . '/..') . DIRECTORY_SEPARATOR . 'upload';
$allowedExt = ['pdf','doc','docx','xls','xlsx','ppt','pptx','jpg','jpeg','png','gif','webp'];
$maxBytes = 25 * 1024 * 1024; // 25MB

/* ===== Email ===== */
function sendSubscriptionEmail($email, $group_name, $group_id, $token, $is_update_notification = false) {
    require_once '../includes/PHPMailer/src/PHPMailer.php';
    require_once '../includes/PHPMailer/src/SMTP.php';
    require_once '../includes/PHPMailer/src/Exception.php';
    $config_mail = include '../includes/config_mail.php';

    $mail = new PHPMailer\PHPMailer\PHPMailer(true);
    $current_domain = "https://" . ($_SERVER['HTTP_HOST'] ?? 'localhost');

    try {
        $mail->isSMTP();
        $mail->Host = $config_mail['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $config_mail['username'];
        $mail->Password = $config_mail['password'];
        $mail->SMTPSecure = $config_mail['encryption'];
        $mail->Port = $config_mail['port'];
        $mail->CharSet = 'UTF-8';
        $mail->isHTML(true);
        $mail->setFrom($config_mail['from_email'], $config_mail['from_name']);
        $mail->addAddress($email);

        if ($is_update_notification) {
            $unsubscribe_link = "$current_domain/unsubscribe.php?token=$token&email=" . urlencode($email);
            $mail->Subject = 'Оновлення розкладу для групи ' . $group_name;
            $mail->Body = "
                <h2>Оновлення розкладу</h2>
                <p>Розклад для групи <strong>$group_name</strong> було оновлено.</p>
                <p>Переглянути: <a href='$current_domain/rozklad/group_schedule.php?id=$group_id'>посилання</a></p>
                <p>Відписатись: <a href='$unsubscribe_link'>тут</a>.</p>
            ";
            $mail->AltBody = "Оновлення розкладу $group_name: $current_domain/rozklad/group_schedule.php?id=$group_id\nВідписатись: $unsubscribe_link";
        } else {
            $mail->Subject = 'Підтвердження підписки на оновлення розкладу';
            $mail->Body = "
                <h2>Підтвердження підписки</h2>
                <p>Ви підписалися на оновлення для групи <strong>$group_name</strong>.</p>
                <p>Підтвердити: <a href='$current_domain/subscription_verify.php?token=$token'>посилання</a></p>
            ";
            $mail->AltBody = "Підтвердження: $current_domain/subscription_verify.php?token=$token";
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Mail error: " . $e->getMessage());
        return false;
    }
}

/* ===================== Повне очищення розкладу групи ===================== */
if ($is_authorized && isset($_POST['clear_all_schedules'])) {
    $stmt = $conn->prepare("DELETE FROM schedules WHERE group_id = ?");
    if ($stmt) {
        $stmt->bind_param("i", $group_id);
        if ($stmt->execute()) {
            $stmt->close();
            header("Location: " . build_return_url($group_id, $selected_day, ['cleared' => 1]));
            exit;
        } else {
            $error = "Не вдалося очистити розклад: " . $stmt->error;
            $stmt->close();
        }
    } else {
        $error = "Помилка підготовки запиту на очищення: " . $conn->error;
    }
}

/* ===================== Редагування одного уроку (з модалки) ===================== */
if ($is_authorized && isset($_POST['save_schedule'])) {
    $post_group_id = (int)($_POST['group_id'] ?? $group_id);
    if ($post_group_id !== $group_id) {
        $error = "Невірні дані форми (group_id).";
    } else {
        $schedule_id = isset($_POST['schedule_id']) ? intval($_POST['schedule_id']) : 0;
        $day_of_week = trim((string)($_POST['day_of_week'] ?? ''));
        $time_slot   = trim((string)($_POST['time_slot'] ?? ''));
        $return_lesson = (int)($_POST['return_lesson'] ?? 0);
        if ($return_lesson < 1 || $return_lesson > 8) $return_lesson = 0;

        if ($day_of_week === '' || !in_array($day_of_week, $days_of_week_full, true)) {
            $error = "Невірний день тижня.";
        } elseif ($time_slot === '') {
            $error = "Невірний часовий слот.";
        } else {
            $subject     = val_or_null($_POST['subject'] ?? '');
            $teacher     = val_or_null($_POST['teacher'] ?? '');
            $room        = val_or_null($_POST['room'] ?? '');
            $replacement = val_or_null($_POST['replacement'] ?? '');
            $teacher_comment = val_or_null($_POST['teacher_comment'] ?? '');

            // multiple links: lesson_links[]
            $linksRaw = $_POST['lesson_links'] ?? [];
            if (!is_array($linksRaw)) {
                $linksRaw = preg_split("/\r\n|\n|\r/", (string)$linksRaw);
                if ($linksRaw === false) $linksRaw = [];
            }
            $links = [];
            foreach ($linksRaw as $lnk) {
                $lnk = trim((string)$lnk);
                if ($lnk !== '') $links[] = $lnk;
            }
            $links = array_values(array_unique($links));
            $lesson_link = !empty($links) ? implode("\n", $links) : null;

            // знайдемо існуючий запис (якщо schedule_id = 0)
            $sid = 0;
            $existing_attach = '';
            if ($schedule_id > 0) {
                $st = $conn->prepare("SELECT id" . ($has_attachment_path ? ", attachment_path" : "") . " FROM schedules WHERE id = ? AND group_id = ? LIMIT 1");
                if ($st) {
                    $st->bind_param("ii", $schedule_id, $group_id);
                    $st->execute();
                    $row = $st->get_result()->fetch_assoc();
                    $st->close();
                    if ($row) {
                        $sid = (int)$row['id'];
                        $existing_attach = (string)($row['attachment_path'] ?? '');
                    }
                }
            }
            if ($sid <= 0) {
                $st = $conn->prepare("SELECT id" . ($has_attachment_path ? ", attachment_path" : "") . " FROM schedules WHERE group_id = ? AND day_of_week = ? AND time_slot = ? LIMIT 1");
                if ($st) {
                    $st->bind_param("iss", $group_id, $day_of_week, $time_slot);
                    $st->execute();
                    $row = $st->get_result()->fetch_assoc();
                    $st->close();
                    if ($row) {
                        $sid = (int)$row['id'];
                        $existing_attach = (string)($row['attachment_path'] ?? '');
                    }
                }
            }

            // upload/delete file
            $delete_attach = isset($_POST['delete_attachment']) && (int)$_POST['delete_attachment'] === 1;
            $new_attach_path = null;

            if ($has_attachment_path && isset($_FILES['attachment']) && is_array($_FILES['attachment'])) {
                $up = handle_upload_one($_FILES['attachment'], $uploadAbsDir, $uploadWebDir, $allowedExt, $maxBytes);
                if (!$up['ok']) {
                    $error = (string)$up['error'];
                } else {
                    $new_attach_path = (string)($up['path'] ?? '');
                }
            } elseif (!$has_attachment_path && isset($_FILES['attachment']) && is_array($_FILES['attachment']) && (string)($_FILES['attachment']['name'] ?? '') !== '') {
                $up = handle_upload_one($_FILES['attachment'], $uploadAbsDir, $uploadWebDir, $allowedExt, $maxBytes);
                if (!$up['ok']) {
                    $error = (string)$up['error'];
                } else {
                    $new_attach_path = (string)($up['path'] ?? '');
                    if ($new_attach_path !== '') {
                        $append = "\n\nФайл: " . $new_attach_path;
                        $teacher_comment = trim((string)($teacher_comment ?? '')) . $append;
                        $teacher_comment = val_or_null($teacher_comment);
                    }
                }
            }

            if (!isset($error) || (string)$error === '') {
                $final_attach = $existing_attach;
                if ($delete_attach) $final_attach = '';
                if (!empty($new_attach_path)) $final_attach = $new_attach_path;
                $final_attach_db = ($final_attach === '') ? null : $final_attach;

                if ($sid > 0) {
                    // UPDATE
                    if ($has_attachment_path) {
                        $sqlu = "UPDATE schedules
                                 SET subject = ?, teacher = ?, room = ?, replacement = ?, lesson_link = ?, teacher_comment = ?, attachment_path = ?
                                 WHERE id = ? AND group_id = ?";
                        $st = $conn->prepare($sqlu);
                        if (!$st) {
                            $error = "Помилка підготовки UPDATE: " . $conn->error;
                        } else {
                            $st->bind_param("sssssssii", $subject, $teacher, $room, $replacement, $lesson_link, $teacher_comment, $final_attach_db, $sid, $group_id);
                            if (!$st->execute()) {
                                $error = "Помилка виконання UPDATE: " . $st->error;
                            }
                            $st->close();
                        }
                    } else {
                        $sqlu = "UPDATE schedules
                                 SET subject = ?, teacher = ?, room = ?, replacement = ?, lesson_link = ?, teacher_comment = ?
                                 WHERE id = ? AND group_id = ?";
                        $st = $conn->prepare($sqlu);
                        if (!$st) {
                            $error = "Помилка підготовки UPDATE: " . $conn->error;
                        } else {
                            $st->bind_param("ssssssii", $subject, $teacher, $room, $replacement, $lesson_link, $teacher_comment, $sid, $group_id);
                            if (!$st->execute()) {
                                $error = "Помилка виконання UPDATE: " . $st->error;
                            }
                            $st->close();
                        }
                    }
                } else {
                    // INSERT
                    if ($has_attachment_path) {
                        $sqli = "INSERT INTO schedules (group_id, day_of_week, time_slot, subject, teacher, room, replacement, lesson_link, teacher_comment, attachment_path)
                                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                        $st = $conn->prepare($sqli);
                        if (!$st) {
                            $error = "Помилка підготовки INSERT: " . $conn->error;
                        } else {
                            $st->bind_param("issssssssss", $group_id, $day_of_week, $time_slot, $subject, $teacher, $room, $replacement, $lesson_link, $teacher_comment, $final_attach_db);
                            if (!$st->execute()) {
                                $error = "Помилка виконання INSERT: " . $st->error;
                            }
                            $st->close();
                        }
                    } else {
                        $sqli = "INSERT INTO schedules (group_id, day_of_week, time_slot, subject, teacher, room, replacement, lesson_link, teacher_comment)
                                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                        $st = $conn->prepare($sqli);
                        if (!$st) {
                            $error = "Помилка підготовки INSERT: " . $conn->error;
                        } else {
                            $st->bind_param("issssssss", $group_id, $day_of_week, $time_slot, $subject, $teacher, $room, $replacement, $lesson_link, $teacher_comment);
                            if (!$st->execute()) {
                                $error = "Помилка виконання INSERT: " . $st->error;
                            }
                            $st->close();
                        }
                    }
                }

                if (!isset($error) || (string)$error === '') {
                    $sql_subscriptions = "SELECT email, verification_token, is_verified FROM subscriptions WHERE group_id = ? AND is_verified = 1";
                    $stmt_sub = $conn->prepare($sql_subscriptions);
                    if ($stmt_sub) {
                        $stmt_sub->bind_param("i", $group_id);
                        $stmt_sub->execute();
                        $subscriptions = $stmt_sub->get_result();
                        while ($sub = $subscriptions->fetch_assoc()) {
                            if (!empty($sub['is_verified'])) {
                                sendSubscriptionEmail($sub['email'], (string)$group['name'], $group_id, (string)$sub['verification_token'], true);
                            }
                        }
                        $stmt_sub->close();
                    }

                    $anchor = ($return_lesson > 0) ? ('lesson-' . $return_lesson) : '';
                    header("Location: " . build_return_url($group_id, $day_of_week, ['saved' => 1], $anchor));
                    exit;
                }
            }
        }
    }
}

/* ===================== Видалення / Очищення полів ===================== */
if ($is_authorized && isset($_POST['delete_schedule'])) {
    $schedule_id = intval($_POST['schedule_id']);
    $sql = "DELETE FROM schedules WHERE id = ? AND group_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $schedule_id, $group_id);
    $stmt->execute();
    $stmt->close();
    header("Location: " . build_return_url($group_id, $selected_day));
    exit;
}

if ($is_authorized && isset($_POST['clear_field'])) {
    $schedule_id = intval($_POST['schedule_id']);
    $field = (string)($_POST['field'] ?? '');

    // дозволено очищати ТІЛЬКИ: заміну, коментар, посилання і файл
    $allowed_fields = ['replacement','teacher_comment','lesson_link'];
    if ($has_attachment_path) $allowed_fields[] = 'attachment_path';

    if (!in_array($field, $allowed_fields, true)) {
        die('Некоректне поле для очищення.');
    }
    $sql = "UPDATE schedules SET {$field} = NULL WHERE id = ? AND group_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $schedule_id, $group_id);
    $stmt->execute();
    $stmt->close();
    header("Location: " . build_return_url($group_id, $selected_day));
    exit;
}

/* ===================== Редагування часових слотів ===================== */
if ($is_authorized && isset($_POST['save_time_slots'])) {
    $lesson_times = [];
    for ($i = 1; $i <= 8; $i++) {
        $start_time = trim((string)($_POST['start_time_' . $i] ?? ''));
        $end_time   = trim((string)($_POST['end_time_' . $i] ?? ''));
        if ($start_time !== '' && $end_time !== '') {
            $lesson_times[$i] = ['start_time' => $start_time, 'end_time' => $end_time];
        }
    }

    $sql = "DELETE FROM lesson_times WHERE group_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $group_id);
    $stmt->execute();
    $stmt->close();

    $sql = "INSERT INTO lesson_times (group_id, lesson_number, start_time, end_time) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    foreach ($lesson_times as $lesson_number => $data) {
        $stmt->bind_param("iiss", $group_id, $lesson_number, $data['start_time'], $data['end_time']);
        $stmt->execute();
    }
    $stmt->close();

    header("Location: " . build_return_url($group_id, $selected_day));
    exit;
}

/* ===================== Завантаження розкладу (тільки обраний день) ===================== */
$schedules = [];
if ($selected_day !== '') {
    $sql = "SELECT * FROM schedules WHERE group_id = ? AND day_of_week = ? ORDER BY time_slot";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("is", $group_id, $selected_day);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($schedule = $result->fetch_assoc()) {
        $schedules[(string)$schedule['time_slot']] = $schedule;
    }
    $stmt->close();
}

$conn->close();

/* ===== підготовка header.php ===== */
$siteName  = 'Розклад занять';
$pageTitle = 'Редагування розкладу — ' . (string)($group['name'] ?? '');
if ($selected_day !== '') $pageTitle .= ' · ' . $selected_day;

$pageCss   = [
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
    '/css/admin.css?v=4',
    '/css/schedule.css?v=2.0.0'
];

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

<style>
/* ===== вибір дня (максимально зручно на телефоні) ===== */
.day-picker{
  border:1px solid rgba(0,0,0,.08);
  background:rgba(255,255,255,.65);
  border-radius:16px;
  padding:.65rem .7rem;
}
.day-grid{
  display:flex;
  flex-wrap:wrap;
  gap:.5rem;
}
.day-btn{
  flex: 1 1 calc(16.666% - .5rem);
  min-width: 54px;
  text-align:center;
  padding:.55rem .25rem;
  border-radius:14px;
  border:1px solid rgba(0,0,0,.14);
  background:#fff;
  text-decoration:none;
  font-weight:800;
  color:#1b1b1b;
  user-select:none;
  -webkit-tap-highlight-color: transparent;
}
.day-btn:active{ transform: translateY(1px); }
.day-btn.active{
  background:#0d6efd;
  color:#fff;
  border-color:#0d6efd;
  box-shadow: 0 8px 18px rgba(13,110,253,.22);
}
@media (max-width: 576px){
  .day-btn{ flex: 1 1 calc(33.333% - .5rem); padding:.65rem .25rem; }
}

/* ===== компактність таблиці на телефоні ===== */
@media (max-width: 576px){
  .schedule-table th, .schedule-table td{ padding:.45rem .5rem; }
  .schedule-table .btn-sm{ padding:.42rem .6rem; }
}
@media (min-width: 576px){
  .w-sm-auto{ width:auto !important; }
}

/* ===== компактність модалки на телефоні ===== */
@media (max-width: 576px) {
  #editLessonModal .modal-dialog { margin: 0; }
  #editLessonModal .modal-content { border-radius: 0; }
  #editLessonModal .modal-header,
  #editLessonModal .modal-body,
  #editLessonModal .modal-footer { padding: .6rem .75rem; }
  #editLessonModal .modal-title { font-size: 1rem; line-height: 1.15; }
  #editLessonModal .small { font-size: .85rem; }
  #editLessonModal .form-label { margin-bottom: .25rem; font-size: .88rem; }
  #editLessonModal .form-control,
  #editLessonModal .form-select { padding: .35rem .55rem; font-size: .95rem; }
  #editLessonModal textarea.form-control { min-height: 64px; }
  #editLessonModal .modal-footer .btn { padding: .4rem .65rem; font-size: .95rem; }
  #editLessonModal .m-links-head { flex-direction: column; align-items: flex-start !important; gap: .35rem !important; }
  #editLessonModal .m-link-row .btn { padding: .35rem .5rem; }
}
/* щоб футер із кнопками не "тікав" і був завжди внизу модалки */
#editLessonModal .modal-footer{
  position: sticky;
  bottom: 0;
  background: inherit;
  z-index: 2;
  border-top: 1px solid rgba(255,255,255,.08);
}
</style>

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

      <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-2 mb-3">
        <div>
          <h1 class="admin-title mb-0">Розклад групи <?= htmlspecialchars((string)$group['name'], ENT_QUOTES, 'UTF-8') ?></h1>
          <div class="small text-muted mt-1">Оберіть день і редагуйте уроки (зручно з телефону).</div>
        </div>

        <?php if ($is_authorized): ?>
        <div class="d-flex gap-2 flex-wrap">
          <a class="btn btn-success btn-sm" href="/admin/weekly_import.php?group_id=<?= (int)$group_id ?>">
            Тижневий імпорт
          </a>

          <form method="POST" onsubmit="return confirm('Ви впевнені, що хочете повністю очистити розклад для цієї групи? Дію не можна скасувати.');">
            <button type="submit" name="clear_all_schedules" class="btn btn-outline-danger btn-sm">
              Очистити розклад
            </button>
          </form>
        </div>
        <?php endif; ?>
      </div>

      <div class="day-picker mb-3">
        <div class="day-grid">
          <?php foreach ($days_of_week_full as $d): ?>
            <a class="day-btn <?= ($d === $selected_day ? 'active' : '') ?>"
               href="dashboard_schedule.php?group_id=<?= (int)$group_id ?>&day=<?= urlencode($d) ?>">
              <?= htmlspecialchars($d, ENT_QUOTES, 'UTF-8') ?>
            </a>
          <?php endforeach; ?>
        </div>
      </div>

      <?php if (isset($_GET['cleared']) && $_GET['cleared'] == '1'): ?>
        <div class="alert alert-success text-center" role="alert">Розклад групи повністю очищено.</div>
      <?php endif; ?>

      <?php if (isset($_GET['import_success'])): ?>
        <div class="alert alert-success text-center" role="alert">
          Імпорт успішний: додано/оновлено <?= (int)$_GET['import_success']; ?> запис(ів).
        </div>
      <?php endif; ?>

      <?php if (isset($_GET['saved']) && $_GET['saved'] === '1'): ?>
        <div class="alert alert-success text-center" role="alert">Зміни збережено.</div>
      <?php endif; ?>

      <?php if (isset($error) && (string)$error !== ''): ?>
        <div class="alert alert-danger text-center" role="alert">
          <?= htmlspecialchars((string)$error, ENT_QUOTES, 'UTF-8'); ?>
        </div>
      <?php endif; ?>

      <?php if ($selected_day === ''): ?>
        <div class="alert alert-info text-center" role="alert">
          Виберіть день тижня вище.
        </div>
      <?php else: ?>

        <section class="card-block mb-3 day-section" id="day-<?= (int)$selected_day_idx; ?>">
          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
            <h2 class="block-title mb-0" data-day="<?= htmlspecialchars($selected_day, ENT_QUOTES, 'UTF-8') ?>">
              <?= htmlspecialchars($selected_day, ENT_QUOTES, 'UTF-8') ?>
            </h2>
          </div>

          <div class="table-responsive mt-2">
            <table class="table table-striped table-hover schedule-table align-middle">
              <thead>
                <tr>
                  <th style="width:44px;">#</th>
                  <th class="d-none d-sm-table-cell" style="width:120px;">Час</th>
                  <th>Предмет</th>
                  <th class="d-none d-sm-table-cell">Викладач</th>
                  <th class="d-none d-md-table-cell">Каб.</th>
                  <th class="d-none d-lg-table-cell">Заміна</th>
                  <th class="d-none d-lg-table-cell">Коментар</th>
                  <th class="d-none d-lg-table-cell">Посилання</th>
                  <?php if ($is_authorized): ?><th style="width:260px;">Дії</th><?php endif; ?>
                </tr>
              </thead>

              <tbody>
              <?php for ($lesson = 1; $lesson <= 8; $lesson++): ?>
                <?php
                  $time_slot = $time_slots[$lesson] ?? '';
                  $schedule  = ($time_slot !== '' && isset($schedules[$time_slot])) ? $schedules[$time_slot] : null;
                  $schedule_id = (int)($schedule['id'] ?? 0);

                  $attach = (string)($schedule['attachment_path'] ?? '');
                  $links_arr = [];
                  if (!empty($schedule['lesson_link'])) {
                      $tmp = preg_split("/\r\n|\n|\r/", (string)$schedule['lesson_link']);
                      if ($tmp !== false) {
                          $tmp = array_map('trim', $tmp);
                          $tmp = array_values(array_filter($tmp, fn($v)=>$v!=='' ));
                          $links_arr = $tmp;
                      }
                  }

                  $btnData = [
                      'id' => $schedule_id,
                      'day' => $selected_day,
                      'time_slot' => (string)$time_slot,
                      'lesson' => $lesson,
                      'day_index' => $selected_day_idx,
                      'subject' => (string)($schedule['subject'] ?? ''),
                      'teacher' => (string)($schedule['teacher'] ?? ''),
                      'room' => (string)($schedule['room'] ?? ''),
                      'replacement' => (string)($schedule['replacement'] ?? ''),
                      'teacher_comment' => (string)($schedule['teacher_comment'] ?? ''),
                      'lesson_link' => (string)($schedule['lesson_link'] ?? ''),
                      'attachment_path' => (string)($schedule['attachment_path'] ?? ''),
                  ];
                ?>

                <tr id="lesson-<?= (int)$lesson; ?>">
                  <td><?= (int)$lesson; ?></td>

                  <td class="d-none d-sm-table-cell">
                    <span class="badge bg-light text-dark time-pill"><?= htmlspecialchars((string)$time_slot, ENT_QUOTES, 'UTF-8'); ?></span>
                  </td>

                  <td class="text-start">
                    <div class="fw-semibold"><?= htmlspecialchars((string)($schedule['subject'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></div>

                    <div class="small text-muted d-sm-none">
                      <?php if ($time_slot !== ''): ?>
                        <span><?= htmlspecialchars((string)$time_slot, ENT_QUOTES, 'UTF-8'); ?></span>
                        ·
                      <?php endif; ?>

                      <?= htmlspecialchars((string)($schedule['teacher'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>

                      <?php if (!empty($schedule['room'])): ?>
                        · каб. <?= htmlspecialchars((string)$schedule['room'], ENT_QUOTES, 'UTF-8'); ?>
                      <?php endif; ?>

                      <?php if (!empty($schedule['replacement'])): ?>
                        · <span class="text-danger fw-semibold">заміна</span>
                      <?php endif; ?>

                      <?php if (!empty($attach)): ?>
                        · <span title="Є файл">📎</span>
                      <?php endif; ?>
                    </div>
                  </td>

                  <td class="d-none d-sm-table-cell"><?= htmlspecialchars((string)($schedule['teacher'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></td>
                  <td class="d-none d-md-table-cell"><?= htmlspecialchars((string)($schedule['room'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></td>
                  <td class="d-none d-lg-table-cell"><?= htmlspecialchars((string)($schedule['replacement'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></td>

                  <td class="d-none d-lg-table-cell">
                    <div><?= htmlspecialchars((string)($schedule['teacher_comment'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></div>
                    <?php if (!empty($attach)): ?>
                      <div class="mt-1">
                        <a href="<?= htmlspecialchars((string)$attach, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener" class="btn btn-sm btn-outline-secondary">📎 Файл</a>
                      </div>
                    <?php endif; ?>
                  </td>

                  <td class="d-none d-lg-table-cell">
                    <?php if (!empty($links_arr)): ?>
                      <?php if (count($links_arr) === 1): ?>
                        <a href="<?= htmlspecialchars((string)$links_arr[0], ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener" class="lesson-button btn btn-sm btn-outline-primary">Перейти</a>
                      <?php else: ?>
                        <a href="<?= htmlspecialchars((string)$links_arr[0], ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener" class="lesson-button btn btn-sm btn-outline-primary">
                          Перейти (<?= (int)count($links_arr); ?>)
                        </a>
                      <?php endif; ?>
                    <?php else: ?>
                      -
                    <?php endif; ?>
                  </td>

                  <?php if ($is_authorized): ?>
                  <td>
                    <div class="d-grid gap-2 d-sm-flex flex-wrap">
                      <button type="button"
                              class="btn btn-primary btn-sm w-100 w-sm-auto js-edit-lesson"
                              data-bs-toggle="modal"
                              data-bs-target="#editLessonModal"
                              data-schedule="<?= htmlspecialchars(json_encode($btnData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8'); ?>">
                        Редагувати
                      </button>

                      <?php if ($schedule_id > 0): ?>
                        <form method="POST" class="d-inline">
                          <input type="hidden" name="schedule_id" value="<?= (int)$schedule_id; ?>">
                          <button type="submit" name="delete_schedule" class="btn btn-outline-danger btn-sm w-100 w-sm-auto"
                                  onclick="return confirm('Ви впевнені, що хочете видалити цей урок?')">
                            Видалити
                          </button>
                        </form>
                      <?php endif; ?>
                    </div>

                    <?php if ($schedule_id > 0): ?>
                      <div class="mt-2 small text-muted">ОЧИСТИТИ</div>
                      <div class="d-flex flex-wrap gap-2 mt-1">
                        <?php
                          $clearMap = ['replacement'=>'Заміна','teacher_comment'=>'Коментар','lesson_link'=>'Посилання'];
                          if ($has_attachment_path) $clearMap['attachment_path'] = 'Файл';
                        ?>
                        <?php foreach ($clearMap as $fld=>$lbl): ?>
                          <form method="POST" class="d-inline">
                            <input type="hidden" name="schedule_id" value="<?= (int)$schedule_id; ?>">
                            <input type="hidden" name="field" value="<?= htmlspecialchars((string)$fld, ENT_QUOTES, 'UTF-8'); ?>">
                            <button type="submit" name="clear_field" class="btn btn-warning btn-sm">
                              <?= htmlspecialchars((string)$lbl, ENT_QUOTES, 'UTF-8'); ?>
                            </button>
                          </form>
                        <?php endforeach; ?>
                      </div>
                    <?php endif; ?>
                  </td>
                  <?php endif; ?>

                </tr>
              <?php endfor; ?>
              </tbody>

            </table>
          </div>
        </section>

      <?php endif; ?>

    </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>

<script>
// single edit modal
document.addEventListener('DOMContentLoaded', function() {

  const editModalEl = document.getElementById('editLessonModal');
  if (!editModalEl) return;

  const fScheduleId = document.getElementById('m_schedule_id');
  const fDay = document.getElementById('m_day_of_week');
  const fTime = document.getElementById('m_time_slot');
  const fReturnLesson = document.getElementById('m_return_lesson');

  const fSubject = document.getElementById('m_subject');
  const fTeacher = document.getElementById('m_teacher');
  const fRoom = document.getElementById('m_room');
  const fReplacement = document.getElementById('m_replacement');
  const fComment = document.getElementById('m_teacher_comment');

  const linksWrap = document.getElementById('m_links_wrap');
  const addLinkBtn = document.getElementById('m_add_link');

  const headDay = document.getElementById('m_head_day');
  const headTime = document.getElementById('m_head_time');
  const headLesson = document.getElementById('m_head_lesson');

  const attachInfo = document.getElementById('m_attach_info');
  const attachLink = document.getElementById('m_attach_link');
  const deleteAttachWrap = document.getElementById('m_delete_attach_wrap');
  const deleteAttach = document.getElementById('m_delete_attachment');
  const attachInput = document.getElementById('m_attachment');

  function splitLinks(s){
    s = (s === null || s === undefined) ? '' : String(s);
    const arr = s.split(/\r?\n/).map(x=>x.trim()).filter(Boolean);
    return Array.from(new Set(arr));
  }

  function addLinkRow(value){
    const v = (value === null || value === undefined) ? '' : String(value);
    const row = document.createElement('div');
    row.className = 'd-flex gap-2 align-items-center mb-2 m-link-row';
    row.innerHTML = `
      <input type="url" class="form-control form-control-sm" name="lesson_links[]" placeholder="https://..." value="${v.replace(/"/g,'&quot;')}">
      <button type="button" class="btn btn-outline-danger btn-sm" title="Видалити посилання">−</button>
    `;
    const btn = row.querySelector('button');
    btn.addEventListener('click', ()=> {
      row.remove();
      if (linksWrap.querySelectorAll('input[name="lesson_links[]"]').length === 0) {
        addLinkRow('');
      }
    });
    linksWrap.appendChild(row);
  }

  if (addLinkBtn) {
    addLinkBtn.addEventListener('click', function(){
      addLinkRow('');
      const last = linksWrap.querySelector('div:last-child input');
      if (last) last.focus();
    });
  }

  document.querySelectorAll('.js-edit-lesson').forEach(btn => {
    btn.addEventListener('click', function(){
      let data = {};
      try {
        data = JSON.parse(this.getAttribute('data-schedule') || '{}');
      } catch(e){ data = {}; }

      const sid = parseInt(data.id || 0, 10) || 0;
      const day = (data.day || '');
      const timeSlot = (data.time_slot || '');
      const lesson = parseInt(data.lesson || 0, 10) || 0;

      if (fScheduleId) fScheduleId.value = sid;
      if (fDay) fDay.value = day;
      if (fTime) fTime.value = timeSlot;
      if (fReturnLesson) fReturnLesson.value = lesson;

      if (fSubject) fSubject.value = (data.subject || '');
      if (fTeacher) fTeacher.value = (data.teacher || '');
      if (fRoom) fRoom.value = (data.room || '');
      if (fReplacement) fReplacement.value = (data.replacement || '');
      if (fComment) fComment.value = (data.teacher_comment || '');

      if (headDay) headDay.textContent = day;
      if (headTime) headTime.textContent = timeSlot;
      if (headLesson) headLesson.textContent = lesson ? String(lesson) : '';

      // links
      if (linksWrap) {
        linksWrap.innerHTML = '';
        const links = splitLinks(data.lesson_link || '');
        if (links.length) {
          links.forEach(l => addLinkRow(l));
        } else {
          addLinkRow('');
        }
      }

      // attachment
      const ap = (data.attachment_path || '');
      if (attachInput) attachInput.value = '';
      if (deleteAttach) deleteAttach.checked = false;

      if (attachInfo && deleteAttachWrap && attachLink) {
        if (ap) {
          attachInfo.classList.remove('d-none');
          deleteAttachWrap.classList.remove('d-none');
          attachLink.href = ap;
          attachLink.textContent = ap;
        } else {
          attachInfo.classList.add('d-none');
          deleteAttachWrap.classList.add('d-none');
          attachLink.href = '#';
          attachLink.textContent = '';
        }
      }
    });
  });

});
</script>

<?php if ($is_authorized && $selected_day !== ''): ?>
<!-- Модалка редагування одного уроку (компактна + fullscreen на sm) -->
<div class="modal fade" id="editLessonModal" tabindex="-1" aria-labelledby="editLessonModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-fullscreen-sm-down modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <div class="d-flex flex-column gap-1">
          <h6 class="modal-title mb-0" id="editLessonModalLabel">Редагувати урок</h6>
          <div class="small text-muted">
            <span class="fw-semibold" id="m_head_day"></span>
            · <span id="m_head_time"></span>
            · Урок № <span id="m_head_lesson"></span>
          </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрити"></button>
      </div>

      <form method="POST" enctype="multipart/form-data" id="editLessonForm"
            action="dashboard_schedule.php?group_id=<?= (int)$group_id; ?>&day=<?= urlencode($selected_day); ?>">
        <div class="modal-body">
          <input type="hidden" name="save_schedule" value="1">
          <input type="hidden" name="group_id" value="<?= (int)$group_id; ?>">
          <input type="hidden" name="schedule_id" id="m_schedule_id" value="0">
          <input type="hidden" name="day_of_week" id="m_day_of_week" value="">
          <input type="hidden" name="time_slot" id="m_time_slot" value="">
          <input type="hidden" name="return_lesson" id="m_return_lesson" value="0">

          <div class="row g-2">
            <div class="col-12 col-md-6">
              <label class="form-label">Предмет</label>
              <input type="text" class="form-control form-control-sm" name="subject" id="m_subject" value="">
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">Викладач</label>
              <input type="text" class="form-control form-control-sm" name="teacher" id="m_teacher" value="">
            </div>

            <div class="col-6 col-md-3">
              <label class="form-label">Кабінет</label>
              <input type="text" class="form-control form-control-sm" name="room" id="m_room" value="">
            </div>

            <div class="col-6 col-md-3">
              <label class="form-label">Заміна</label>
              <input type="text" class="form-control form-control-sm" name="replacement" id="m_replacement" value="">
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">Коментар викладача</label>
              <textarea class="form-control form-control-sm" name="teacher_comment" id="m_teacher_comment" rows="2" placeholder="Коротко..."></textarea>
            </div>

            <div class="col-12">
              <div class="d-flex align-items-center justify-content-between gap-2 m-links-head">
                <label class="form-label mb-0">Посилання</label>
                <button type="button" class="btn btn-sm btn-outline-primary" id="m_add_link">+ Додати посилання</button>
              </div>
              <div class="mt-2" id="m_links_wrap"></div>
              <div class="small text-muted">Можна додати декілька посилань. Кожне збережеться окремим рядком.</div>
            </div>

            <div class="col-12">
              <label class="form-label">Прикріпити файл (до 25 МБ)</label>
              <input type="file" class="form-control form-control-sm" name="attachment" id="m_attachment"
                     accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.webp">
              <div class="small text-muted mt-1">PDF, Word, Excel, PowerPoint, зображення.</div>

              <div class="mt-2 d-none" id="m_attach_info">
                <div class="small text-muted">
                  Поточний файл: <a href="#" target="_blank" rel="noopener" id="m_attach_link"></a>
                </div>
              </div>

              <div class="form-check mt-2 d-none" id="m_delete_attach_wrap">
                <input class="form-check-input" type="checkbox" value="1" name="delete_attachment" id="m_delete_attachment">
                <label class="form-check-label" for="m_delete_attachment">Видалити поточний файл</label>
              </div>
            </div>

          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Скасувати</button>
          <button type="submit" class="btn btn-primary btn-sm">Зберегти</button>
        </div>
      </form>

    </div>
  </div>
</div>
<?php endif; ?>

</body>
</html>

