<?php
// /admin/dashboard_consultations.php
session_start();

date_default_timezone_set('Europe/Kyiv');

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

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

$user_id = (int)$_SESSION['user_id'];

/* ===== хелпер активної вкладки ===== */
function adminActiveTab(string $file): string {
    $self = basename($_SERVER['PHP_SELF']);
    return $self === $file ? ' class="nav-link active"' : ' class="nav-link"';
}

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

/* ===== створення (кілька дат) ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_consultation'])) {
    $group_id       = (int)($_POST['group_id'] ?? 0);
    $lesson_number  = (int)($_POST['lesson_number'] ?? 0);
    $subject_name   = trim((string)($_POST['subject_name'] ?? ''));
    $notes          = trim((string)($_POST['notes'] ?? ''));
    $dates          = $_POST['dates'] ?? [];

    if (!is_array($dates)) $dates = [$dates];

    $valid_rows = [];
    foreach ($dates as $d) {
        $d = trim((string)$d);
        $dt = DateTime::createFromFormat('Y-m-d', $d);
        if ($dt && $dt->format('Y-m-d') === $d) {
            $dow = (int)$dt->format('N'); // 1..7
            if ($dow >= 1 && $dow <= 6) { // Пн..Сб
                $valid_rows[] = ['date' => $dt->format('Y-m-d'), 'dow' => $dow];
            }
        }
    }

    if (!empty($valid_rows) && $group_id > 0 && $lesson_number > 0 && $subject_name !== '') {
        $stmt = $conn->prepare(
            "INSERT INTO consultations (group_id, subject_name, day_of_week, lesson_number, date, notes, user_id)
             VALUES (?,?,?,?,?,?,?)"
        );
        if ($stmt) {
            foreach ($valid_rows as $row) {
                $stmt->bind_param(
                    "isiissi",
                    $group_id,
                    $subject_name,
                    $row['dow'],
                    $lesson_number,
                    $row['date'],
                    $notes,
                    $user_id
                );
                $stmt->execute();
            }
            $stmt->close();
        }
        header("Location: dashboard_consultations.php");
        exit;
    }
}

/* ===== редагування (одна консультація) ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_consultation'])) {
    $consultation_id   = (int)($_POST['consultation_id'] ?? 0);
    $new_date          = trim((string)($_POST['new_date'] ?? ''));
    $new_subject_name  = trim((string)($_POST['new_subject_name'] ?? ''));
    $new_notes         = trim((string)($_POST['new_notes'] ?? ''));

    $dt = DateTime::createFromFormat('Y-m-d', $new_date);
    $new_day = ($dt && $dt->format('Y-m-d') === $new_date) ? (int)$dt->format('N') : 0;

    if ($consultation_id > 0 && $new_date !== '' && $new_subject_name !== '' && $new_day >= 1 && $new_day <= 6) {
        $stmt = $conn->prepare(
            "UPDATE consultations
             SET date = ?, subject_name = ?, day_of_week = ?, notes = ?
             WHERE id = ? AND user_id = ?"
        );
        if ($stmt) {
            $stmt->bind_param("ssisii", $new_date, $new_subject_name, $new_day, $new_notes, $consultation_id, $user_id);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: dashboard_consultations.php");
        exit;
    }
}

/* ===== видалення ===== */
if (isset($_GET['delete'], $_GET['consultation_id'])) {
    $consultation_id = (int)$_GET['consultation_id'];
    if ($consultation_id > 0) {
        $stmt = $conn->prepare("DELETE FROM consultations WHERE id = ? AND user_id = ?");
        if ($stmt) {
            $stmt->bind_param("ii", $consultation_id, $user_id);
            $stmt->execute();
            $stmt->close();
        }
    }
    header("Location: dashboard_consultations.php");
    exit;
}

/* ===== мої консультації ===== */
$consultations = [];
$stmt = $conn->prepare("SELECT * FROM consultations WHERE user_id = ? ORDER BY date");
if ($stmt) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $r = $stmt->get_result();
    while ($row = $r->fetch_assoc()) $consultations[] = $row;
    $stmt->close();
}

$conn->close();

/* ===== довідники ===== */
$consultation_times = [
    7 => '15:30–16:15',
    8 => '16:20–17:05'
];
$days_full = ['Понеділок','Вівторок','Середа','Четвер','П’ятниця','Субота']; // 1..6

/* ===== header vars ===== */
$siteName  = 'Розклад занять';
$pageTitle = 'Консультації — Адмін-панель';
$pageCss   = [
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
    '/css/admin.css?v=4',
    '/css/admin_consultations.css?v=2'
];

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

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

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

      <h1 class="admin-title mb-3">Консультації</h1>

      <!-- створення -->
      <section class="card-block mb-4">
        <h2 class="block-title mb-3">Створити графік консультацій</h2>

        <form method="POST" id="consultationForm">
          <div class="row g-3">
            <div class="col-md-6">
              <label for="group_id" class="form-label">Оберіть групу</label>
              <select class="form-select" id="group_id" name="group_id" required>
                <option value="">— Оберіть групу —</option>
                <?php foreach ($groups as $g): ?>
                  <option value="<?= (int)$g['id'] ?>"><?= htmlspecialchars((string)$g['name'], ENT_QUOTES, 'UTF-8') ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-md-6">
              <label for="lesson_number" class="form-label">Номер уроку</label>
              <select class="form-select" id="lesson_number" name="lesson_number" required>
                <option value="7">7-й урок (<?= htmlspecialchars($consultation_times[7], ENT_QUOTES, 'UTF-8') ?>)</option>
                <option value="8">8-й урок (<?= htmlspecialchars($consultation_times[8], ENT_QUOTES, 'UTF-8') ?>)</option>
              </select>
            </div>

            <div class="col-md-6">
              <label for="subject_name" class="form-label">Предмет</label>
              <input type="text" class="form-control" id="subject_name" name="subject_name" required>
            </div>

            <div class="col-md-6">
              <label for="notes" class="form-label">Примітка (текст або посилання)</label>
              <input type="text" class="form-control" id="notes" name="notes">
            </div>

            <div class="col-12">
              <label class="form-label">Дати консультацій</label>
              <div id="dateInputs" class="d-flex flex-wrap gap-2">
                <input type="date" class="form-control admin-date" name="dates[]" required>
              </div>

              <div class="mt-2 d-flex gap-2 flex-wrap">
                <button type="button" class="btn btn-success admin-w-btn" id="addDate">Додати дату</button>
                <button type="button" class="btn btn-danger admin-w-btn d-none" id="removeDate">Видалити дату</button>
              </div>

              <p class="text-muted mt-2 mb-0">Можна додати кілька дат для одного предмета/уроку.</p>
            </div>

            <div class="col-12">
              <button type="submit" name="save_consultation" class="btn btn-primary admin-w-btn">Зберегти</button>
            </div>
          </div>
        </form>
      </section>

      <!-- список -->
      <section class="card-block">
        <h2 class="block-title mb-3">Мої консультації</h2>

        <?php if (!empty($consultations)): ?>
          <div class="table-responsive">
            <table class="table align-middle admin-table">
              <thead>
                <tr>
                  <th>Дата</th>
                  <th>День</th>
                  <th>Предмет</th>
                  <th>Час</th>
                  <th>Примітка</th>
                  <th class="min-w-160">Дії</th>
                </tr>
              </thead>
              <tbody>
              <?php foreach ($consultations as $c):
                $dateYmd = (string)($c['date'] ?? '');
                $dt = DateTime::createFromFormat('Y-m-d', $dateYmd);
                $date_h = $dt ? $dt->format('d.m.Y') : $dateYmd;

                $dow = (int)($c['day_of_week'] ?? 0); // 1..6
                $day_name = $days_full[$dow - 1] ?? '—';

                $time_h = $consultation_times[(int)($c['lesson_number'] ?? 0)] ?? '—';

                $sid = (int)($c['id'] ?? 0);
                $subj = (string)($c['subject_name'] ?? '');
                $notesVal = (string)($c['notes'] ?? '');
              ?>
                <tr>
                  <td><strong><?= htmlspecialchars($date_h, ENT_QUOTES, 'UTF-8') ?></strong></td>
                  <td><?= htmlspecialchars($day_name, ENT_QUOTES, 'UTF-8') ?></td>
                  <td><?= htmlspecialchars($subj, ENT_QUOTES, 'UTF-8') ?></td>
                  <td><?= htmlspecialchars($time_h, ENT_QUOTES, 'UTF-8') ?></td>
                  <td class="text-break"><?= htmlspecialchars($notesVal, ENT_QUOTES, 'UTF-8') ?></td>
                  <td>
                    <div class="d-flex flex-wrap gap-2">
                      <button
                        type="button"
                        class="btn btn-warning btn-sm js-edit"
                        data-bs-toggle="modal"
                        data-bs-target="#editModal"
                        data-id="<?= $sid ?>"
                        data-date="<?= htmlspecialchars($dateYmd, ENT_QUOTES, 'UTF-8') ?>"
                        data-subject="<?= htmlspecialchars($subj, ENT_QUOTES, 'UTF-8') ?>"
                        data-notes="<?= htmlspecialchars($notesVal, ENT_QUOTES, 'UTF-8') ?>"
                      >
                        Редагувати
                      </button>

                      <a class="btn btn-danger btn-sm"
                         href="?delete=1&consultation_id=<?= $sid ?>"
                         onclick="return confirm('Видалити консультацію?')">
                        Видалити
                      </a>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php else: ?>
          <p class="text-muted mb-0">Поки що консультацій немає.</p>
        <?php endif; ?>
      </section>

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

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

<!-- ОДНА модалка (поза таблицею) -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
    <div class="modal-content">
      <form method="POST" id="editForm">
        <div class="modal-header">
          <h5 class="modal-title" id="editModalLabel">Редагувати консультацію</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрити"></button>
        </div>

        <div class="modal-body">
          <input type="hidden" name="consultation_id" id="edit_consultation_id" value="">
          <input type="hidden" name="edit_consultation" value="1">

          <div class="mb-3">
            <label class="form-label">Дата</label>
            <input type="date" class="form-control" name="new_date" id="edit_new_date" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Предмет</label>
            <input type="text" class="form-control" name="new_subject_name" id="edit_new_subject" required>
          </div>

          <div class="mb-0">
            <label class="form-label">Примітка</label>
            <input type="text" class="form-control" name="new_notes" id="edit_new_notes">
          </div>
        </div>

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

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

<script>
(function() {
  // поля дат
  let count = 1;
  const maxCount = 10;
  const addBtn = document.getElementById('addDate');
  const remBtn = document.getElementById('removeDate');
  const box = document.getElementById('dateInputs');

  function toggleRemove() {
    if (count > 1) remBtn.classList.remove('d-none');
    else remBtn.classList.add('d-none');
  }

  addBtn?.addEventListener('click', () => {
    if (count >= maxCount) {
      alert('Досягнуто максимум дат (10).');
      return;
    }
    const input = document.createElement('input');
    input.type = 'date';
    input.name = 'dates[]';
    input.required = true;
    input.className = 'form-control admin-date';
    box.appendChild(input);
    count++;
    toggleRemove();
  });

  remBtn?.addEventListener('click', () => {
    if (count <= 1) return;
    box.removeChild(box.lastElementChild);
    count--;
    toggleRemove();
  });

  // заповнення ОДНІЄЇ модалки
  const editModal = document.getElementById('editModal');
  editModal?.addEventListener('show.bs.modal', function (event) {
    const btn = event.relatedTarget;
    if (!btn) return;

    const id = btn.getAttribute('data-id') || '';
    const date = btn.getAttribute('data-date') || '';
    const subject = btn.getAttribute('data-subject') || '';
    const notes = btn.getAttribute('data-notes') || '';

    document.getElementById('edit_consultation_id').value = id;
    document.getElementById('edit_new_date').value = date;      // YYYY-MM-DD
    document.getElementById('edit_new_subject').value = subject;
    document.getElementById('edit_new_notes').value = notes;
  });
})();
</script>

</body>
</html>
