<?php
session_start();

require_once '../includes/db_config.php';
require_once '../includes/PHPMailer/src/PHPMailer.php';
require_once '../includes/PHPMailer/src/Exception.php';
require_once '../includes/PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$config_mail = include '../includes/config_mail.php';

/* ======= Доступ для редакторів (адмін/викладач) ======= */
$is_authorized = isset($_SESSION['user_id']) && in_array(($_SESSION['role'] ?? ''), ['admin','teacher'], true);
if (!$is_authorized) {
    header("Location: group_schedule.php?id=" . (int)($_GET['id'] ?? 0));
    exit;
}
/* ====================================================== */

/** Поточний домен (http/https, враховує проксі) */
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$current_domain = $scheme . '://' . $host;

/** ID групи + день */
$group_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$days_of_week = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
$day = isset($_GET['day']) ? trim((string)$_GET['day']) : '';

if ($group_id <= 0) {
    die("Група не вказана. Перевір URL або звернися до адміністратора.");
}
if ($day === '' || !in_array($day, $days_of_week, true)) {
    header("Location: group_schedule.php?id={$group_id}");
    exit;
}

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

function mb_trunc(string $s, int $len = 7000): string {
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        return (mb_strlen($s, 'UTF-8') > $len) ? (mb_substr($s, 0, $len, 'UTF-8') . '…') : $s;
    }
    return (strlen($s) > $len) ? (substr($s, 0, $len) . '…') : $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($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 sendUpdateEmailToSubscribers(array $emails, string $groupName, int $groupId, string $currentDomain, array $config_mail): void {
    if (empty($emails)) return;

    foreach ($emails as $email) {
        $email = trim((string)$email);
        if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) continue;

        $mail = new PHPMailer(true);
        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->setFrom($config_mail['from_email'], $config_mail['from_name']);
            $mail->addAddress($email);

            $mail->isHTML(true);
            $mail->Subject = 'Оновлення розкладу для групи ' . $groupName;

            $view_link = $currentDomain . '/rozklad/group_schedule.php?id=' . $groupId;
            $unsubscribe_link = $currentDomain . '/unsubscribe.php?email=' . urlencode($email) . '&group_id=' . $groupId;

            $gn = htmlspecialchars($groupName, ENT_QUOTES, 'UTF-8');
            $mail->Body = "
                <h2>Оновлення розкладу</h2>
                <p>Розклад для групи <strong>{$gn}</strong> було оновлено.</p>
                <p><a href='{$view_link}'>Переглянути розклад</a></p>
                <p style='margin-top:12px; font-size:12px; color:#666;'>Відписатися: <a href='{$unsubscribe_link}'>тут</a></p>
            ";
            $mail->AltBody = "Оновлення розкладу для групи {$groupName}: {$view_link}\nВідписатися: {$unsubscribe_link}";

            $mail->send();
        } catch (Exception $e) {
            error_log("Помилка надсилання листа оновлення: {$mail->ErrorInfo}");
        }
    }
}

/** Група */
$sql = "SELECT name FROM `groups` WHERE id = ? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $group_id);
$stmt->execute();
$group = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$group) {
    die("Група не знайдена. Перевір URL або звернися до адміністратора.");
}

/** Часові слоти */
$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_time = substr((string)$slot['start_time'], 0, 5);
    $end_time   = substr((string)$slot['end_time'], 0, 5);
    $time_slots[(int)$slot['lesson_number']] = sprintf("%s–%s", $start_time, $end_time);
}
$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'
    ];
}

/** Розклад обраного дня */
$daySchedules = []; // key time_slot
$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, $day);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $daySchedules[(string)$row['time_slot']] = $row;
}
$stmt->close();

$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

$err = '';
$saved = false;

/** Збереження (1 крок) */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_day_changes'])) {

    $updated_count = 0;

    for ($lesson = 1; $lesson <= 8; $lesson++) {
        $time_slot = (string)($time_slots[$lesson] ?? '');
        if ($time_slot === '') continue;

        $existing = $daySchedules[$time_slot] ?? null;
        $existing_id = (int)($existing['id'] ?? 0);

        $replacement = val_or_null($_POST['replacement'][$lesson] ?? '');
        $lesson_link = val_or_null($_POST['lesson_link'][$lesson] ?? '');
        $teacher_comment = val_or_null($_POST['teacher_comment'][$lesson] ?? '');

        $existing_attach = (string)($existing['attachment_path'] ?? '');
        $delete_attach = (int)($_POST['delete_attachment'][$lesson] ?? 0) === 1;

        // Якщо заміну прибрали — чистимо все (посилання/комент/файл теж)
        if ($replacement === null) {
            $lesson_link = null;
            $teacher_comment = null;
            $delete_attach = true;
        }

        // Upload (only if replacement exists AND file provided)
        $new_attach_path = null;
        if ($replacement !== null && isset($_FILES['attachment']['name'][$lesson]) && (string)$_FILES['attachment']['name'][$lesson] !== '') {
            $one = [
                'name' => $_FILES['attachment']['name'][$lesson] ?? '',
                'type' => $_FILES['attachment']['type'][$lesson] ?? '',
                'tmp_name' => $_FILES['attachment']['tmp_name'][$lesson] ?? '',
                'error' => $_FILES['attachment']['error'][$lesson] ?? UPLOAD_ERR_NO_FILE,
                'size' => $_FILES['attachment']['size'][$lesson] ?? 0,
            ];
            $up = handle_upload_one($one, $uploadAbsDir, $uploadWebDir, $allowedExt, $maxBytes);
            if (!$up['ok']) {
                $err = "Урок №{$lesson}: " . (string)$up['error'];
                break;
            }
            $new_attach_path = (string)($up['path'] ?? '');
            if ($new_attach_path !== '' && !$has_attachment_path) {
                $extra = "\n\nФайл: " . $new_attach_path;
                $teacher_comment = mb_trunc(trim((string)($teacher_comment ?? '')) . $extra, 7000);
            }
        }

        if ($err !== '') break;

        // attachment final
        $final_attach = $existing_attach;
        if ($delete_attach) $final_attach = '';
        if (!empty($new_attach_path)) $final_attach = $new_attach_path;

        // Нічого не треба зберігати взагалі
        if ($existing_id <= 0 && $replacement === null && $lesson_link === null && $teacher_comment === null && $final_attach === '') {
            continue;
        }

        if ($existing_id > 0) {
            if ($has_attachment_path) {
                $sqlu = "UPDATE schedules SET replacement = ?, lesson_link = ?, teacher_comment = ?, attachment_path = ? WHERE id = ? AND group_id = ?";
                $st = $conn->prepare($sqlu);
                if ($st) {
                    $final_attach_db = ($final_attach === '') ? null : $final_attach;
                    $st->bind_param("ssssii", $replacement, $lesson_link, $teacher_comment, $final_attach_db, $existing_id, $group_id);
                    if ($st->execute()) $updated_count++;
                    $st->close();
                }
            } else {
                $sqlu = "UPDATE schedules SET replacement = ?, lesson_link = ?, teacher_comment = ? WHERE id = ? AND group_id = ?";
                $st = $conn->prepare($sqlu);
                if ($st) {
                    $st->bind_param("sssii", $replacement, $lesson_link, $teacher_comment, $existing_id, $group_id);
                    if ($st->execute()) $updated_count++;
                    $st->close();
                }
            }
        } else {
            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 (?, ?, ?, NULL, NULL, NULL, ?, ?, ?, ?)";
                $st = $conn->prepare($sqli);
                if ($st) {
                    $final_attach_db = ($final_attach === '') ? null : $final_attach;
                    $st->bind_param("issssss", $group_id, $day, $time_slot, $replacement, $lesson_link, $teacher_comment, $final_attach_db);
                    if ($st->execute()) $updated_count++;
                    $st->close();
                }
            } else {
                $sqli = "INSERT INTO schedules (group_id, day_of_week, time_slot, subject, teacher, room, replacement, lesson_link, teacher_comment)
                         VALUES (?, ?, ?, NULL, NULL, NULL, ?, ?, ?)";
                $st = $conn->prepare($sqli);
                if ($st) {
                    $st->bind_param("isssss", $group_id, $day, $time_slot, $replacement, $lesson_link, $teacher_comment);
                    if ($st->execute()) $updated_count++;
                    $st->close();
                }
            }
        }
    }

    if ($err === '') {
        if ($updated_count > 0) {
            $emails = [];
            $stsub = $conn->prepare("SELECT email FROM subscriptions WHERE group_id = ? AND is_verified = 1");
            if ($stsub) {
                $stsub->bind_param("i", $group_id);
                $stsub->execute();
                $r = $stsub->get_result();
                while ($row = $r->fetch_assoc()) {
                    if (!empty($row['email'])) $emails[] = (string)$row['email'];
                }
                $stsub->close();
            }

            sendUpdateEmailToSubscribers(
                $emails,
                (string)($group['name'] ?? ''),
                (int)$group_id,
                $current_domain,
                (array)$config_mail
            );
        }

        // Після збереження — редірект назад у розклад дня з "saved=1"
        header("Location: group_schedule.php?id={$group_id}&day=" . urlencode($day) . "&saved=1");
        exit;
    }
}

/* ===== Підготовка для header.php ===== */
$siteName  = 'Розклад занять';
$pageTitle = 'Редагування дня ' . $day . ' — ' . (string)($group['name'] ?? '');
$pageCss   = [
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
    '/css/rozklad-schedule.css?v=3'
];

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

<main class="page">
  <div class="kp-container">
    <div class="container my-3 my-sm-4 schedule-wrap">

      <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-2">
        <div>
          <h1 class="h4 mb-1">
            Редагування дня: <span class="text-primary"><?php echo htmlspecialchars($day, ENT_QUOTES, 'UTF-8'); ?></span>
          </h1>
          <div class="text-body-secondary small">
            Група: <strong><?php echo htmlspecialchars((string)($group['name'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></strong>
          </div>
        </div>

        <div class="d-flex gap-2 flex-wrap">
          <a class="btn btn-outline-secondary btn-sm" href="group_schedule.php?id=<?php echo (int)$group_id; ?>&day=<?php echo urlencode($day); ?>">
            ← Назад до розкладу дня
          </a>
          <a class="btn btn-outline-secondary btn-sm" href="group_schedule.php?id=<?php echo (int)$group_id; ?>">
            ← До вибору дня
          </a>
        </div>
      </div>

      <?php if ($err !== ''): ?>
        <div class="alert alert-danger mt-3" role="alert">
          <?php echo htmlspecialchars($err, ENT_QUOTES, 'UTF-8'); ?>
        </div>
      <?php endif; ?>

      <style>
        .lesson-card{border:1px solid rgba(0,0,0,.12);border-radius:14px;padding:.8rem .85rem;background:#fff}
        .tiny-label{font-size:.78rem;color:#6c757d;margin-bottom:.12rem}
        .file-mini{font-size:.82rem;color:#6c757d}
        .file-mini a{word-break:break-all}
        .muted-box{background:rgba(13,110,253,.06);border:1px dashed rgba(13,110,253,.25);border-radius:12px;padding:.55rem .65rem}
        .mat-disabled{opacity:.55}
        .badge-num{font-weight:900}
        .subject-mini{font-size:.9rem;font-weight:700;line-height:1.2}
        .time-mini{font-size:.82rem;color:#6c757d}
        .req-note{font-size:.82rem;color:#6c757d;margin-top:.25rem}
      </style>

      <div class="muted-box mt-3">
        <div class="small">
          Матеріали (посилання/коментар/файл) можна додавати лише якщо заповнена <strong>“Заміна”</strong>.
        </div>
      </div>

      <form method="POST" enctype="multipart/form-data" class="mt-3">
        <input type="hidden" name="save_day_changes" value="1">

        <div class="d-flex flex-column gap-2">
          <?php for ($lesson = 1; $lesson <= 8; $lesson++): ?>
            <?php
              $time_slot = (string)($time_slots[$lesson] ?? '');
              $existing = ($time_slot !== '' && isset($daySchedules[$time_slot])) ? $daySchedules[$time_slot] : null;

              // якщо це постбек з помилкою — беремо введені значення
              $repVal  = isset($_POST['replacement'][$lesson]) ? (string)$_POST['replacement'][$lesson] : (string)($existing['replacement'] ?? '');
              $linkVal = isset($_POST['lesson_link'][$lesson]) ? (string)$_POST['lesson_link'][$lesson] : (string)($existing['lesson_link'] ?? '');
              $commVal = isset($_POST['teacher_comment'][$lesson]) ? (string)$_POST['teacher_comment'][$lesson] : (string)($existing['teacher_comment'] ?? '');

              $attachVal = (string)($existing['attachment_path'] ?? '');
              $subject = (string)($existing['subject'] ?? '');

              $hasRep = trim($repVal) !== '';
            ?>

            <div class="lesson-card" data-lesson="<?php echo (int)$lesson; ?>">
              <div class="d-flex align-items-start justify-content-between gap-2 flex-wrap mb-2">
                <div class="d-flex align-items-center gap-2 flex-wrap">
                  <span class="badge bg-primary badge-num">№ <?php echo (int)$lesson; ?></span>
                  <?php if ($time_slot !== ''): ?>
                    <span class="time-mini"><?php echo htmlspecialchars($time_slot, ENT_QUOTES, 'UTF-8'); ?></span>
                  <?php endif; ?>
                </div>

                <?php if ($subject !== ''): ?>
                  <div class="text-body-secondary small">
                    <?php echo htmlspecialchars($subject, ENT_QUOTES, 'UTF-8'); ?>
                  </div>
                <?php endif; ?>
              </div>

              <div class="mb-2">
                <div class="tiny-label">Заміна</div>
                <input type="text"
                       class="form-control form-control-sm js-repl"
                       name="replacement[<?php echo (int)$lesson; ?>]"
                       value="<?php echo htmlspecialchars($repVal, ENT_QUOTES, 'UTF-8'); ?>"
                       placeholder="Введіть заміну"
                       data-lesson="<?php echo (int)$lesson; ?>">
                <div class="req-note">Якщо “Заміна” порожня — матеріали не зберігаються.</div>
              </div>

              <div class="row g-2 js-mat <?php echo $hasRep ? '' : 'mat-disabled'; ?>" data-lesson="<?php echo (int)$lesson; ?>">
                <div class="col-12">
                  <div class="tiny-label">Посилання</div>
                  <input type="url"
                         class="form-control form-control-sm js-mat-input"
                         name="lesson_link[<?php echo (int)$lesson; ?>]"
                         value="<?php echo htmlspecialchars($linkVal, ENT_QUOTES, 'UTF-8'); ?>"
                         placeholder="https://..."
                         <?php echo $hasRep ? '' : 'disabled'; ?>>
                </div>

                <div class="col-12">
                  <div class="tiny-label">Коментар</div>
                  <textarea class="form-control form-control-sm js-mat-input"
                            name="teacher_comment[<?php echo (int)$lesson; ?>]"
                            rows="2"
                            placeholder="Коротко..."
                            <?php echo $hasRep ? '' : 'disabled'; ?>><?php echo htmlspecialchars($commVal, ENT_QUOTES, 'UTF-8'); ?></textarea>
                </div>

                <div class="col-12">
                  <div class="tiny-label">Файл (до 25 МБ)</div>
                  <input class="form-control form-control-sm js-mat-input"
                         type="file"
                         name="attachment[<?php echo (int)$lesson; ?>]"
                         accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.webp"
                         <?php echo $hasRep ? '' : 'disabled'; ?>>
                  <div class="file-mini mt-1">PDF, Word, Excel, PowerPoint, зображення.</div>
                </div>

                <?php if ($attachVal !== ''): ?>
                  <div class="col-12">
                    <div class="d-flex align-items-center justify-content-between gap-2 flex-wrap">
                      <div class="file-mini">
                        Поточний файл:
                        <a href="<?php echo htmlspecialchars($attachVal, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener">
                          <?php echo htmlspecialchars($attachVal, ENT_QUOTES, 'UTF-8'); ?>
                        </a>
                      </div>
                      <label class="form-check-label small">
                        <input class="form-check-input me-1 js-mat-input"
                               type="checkbox"
                               name="delete_attachment[<?php echo (int)$lesson; ?>]"
                               value="1"
                               <?php echo $hasRep ? '' : 'disabled'; ?>>
                        Видалити
                      </label>
                    </div>
                  </div>
                <?php endif; ?>
              </div>

            </div>
          <?php endfor; ?>
        </div>

        <div class="d-flex justify-content-end gap-2 mt-3">
          <a class="btn btn-outline-secondary" href="group_schedule.php?id=<?php echo (int)$group_id; ?>&day=<?php echo urlencode($day); ?>">
            Скасувати
          </a>
          <button type="submit" class="btn btn-primary">
            Зберегти
          </button>
        </div>
      </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>

<script>
document.addEventListener('DOMContentLoaded', function(){
  function toggleLesson(lesson){
    var repl = document.querySelector('.js-repl[data-lesson="'+lesson+'"]');
    if (!repl) return;

    var hasRep = (repl.value || '').trim() !== '';

    var mat = document.querySelector('.js-mat[data-lesson="'+lesson+'"]');
    if (!mat) return;

    mat.classList.toggle('mat-disabled', !hasRep);

    var inputs = mat.querySelectorAll('.js-mat-input');
    inputs.forEach(function(el){
      el.disabled = !hasRep;
    });
  }

  var repls = document.querySelectorAll('.js-repl');
  repls.forEach(function(inp){
    var lesson = inp.getAttribute('data-lesson');
    toggleLesson(lesson);

    inp.addEventListener('input', function(){
      toggleLesson(lesson);
    });
    inp.addEventListener('change', function(){
      toggleLesson(lesson);
    });
  });
});
</script>

</body>
</html>
