<?php
// /admin/edit_teacher_profile.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'] ?? ''));
if (!isset($_SESSION['user_id']) || !in_array($role, ['teacher','admin'], true)) {
    header("Location: ../login.php");
    exit;
}

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

/* ===== helpers ===== */
function sanitize_dirname(string $name): string {
    $map = [
        'А'=>'A','Б'=>'B','В'=>'V','Г'=>'H','Ґ'=>'G','Д'=>'D','Е'=>'E','Є'=>'Ye','Ж'=>'Zh','З'=>'Z','И'=>'Y','І'=>'I','Ї'=>'Yi','Й'=>'Y',
        'К'=>'K','Л'=>'L','М'=>'M','Н'=>'N','О'=>'O','П'=>'P','Р'=>'R','С'=>'S','Т'=>'T','У'=>'U','Ф'=>'F','Х'=>'Kh','Ц'=>'Ts','Ч'=>'Ch','Ш'=>'Sh','Щ'=>'Shch','Ю'=>'Yu','Я'=>'Ya',
        'а'=>'a','б'=>'b','в'=>'v','г'=>'h','ґ'=>'g','д'=>'d','е'=>'e','є'=>'ie','ж'=>'zh','з'=>'z','и'=>'y','і'=>'i','ї'=>'i','й'=>'i',
        'к'=>'k','л'=>'l','м'=>'m','н'=>'n','о'=>'o','п'=>'p','р'=>'r','с'=>'s','т'=>'t','у'=>'u','ф'=>'f','х'=>'kh','ц'=>'ts','ч'=>'ch','ш'=>'sh','щ'=>'shch','ю'=>'iu','я'=>'ia',
        '’'=>"", "'"=>"", "ʼ"=>""
    ];
    $t = strtr($name, $map);
    $t = preg_replace('~[^a-zA-Z0-9\-\._ ]+~u', '', $t);
    $t = trim(preg_replace('~\s+~', ' ', (string)$t));
    $t = str_replace(' ', '_', $t);
    if ($t === '') $t = 'user';
    return $t;
}

function json_pairs_from_post(array $subjects, array $links): array {
    $pairs = [];
    $n = max(count($subjects), count($links));
    for ($i = 0; $i < $n; $i++) {
        $s = trim((string)($subjects[$i] ?? ''));
        $l = trim((string)($links[$i] ?? ''));
        if ($s === '' && $l === '') continue;
        $pairs[] = ['subject' => $s, 'link' => $l];
    }
    return $pairs;
}

/* ===== поточні дані ===== */
$sql = "SELECT full_name, email, subjects, website_links,
        CASE
            WHEN (SELECT COUNT(*) FROM information_schema.COLUMNS
                  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='users' AND COLUMN_NAME='avatar_path') > 0
            THEN avatar_path ELSE NULL
        END AS avatar_path
        FROM users
        WHERE id = ? AND (role='teacher' OR role='admin')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $teacher_id);
$stmt->execute();
$teacher = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$teacher) { die("Користувач не знайдений. Зверніться до адміністратора."); }

/* ===== існуючі пари (JSON) ===== */
$existing_pairs = [];
if (!empty($teacher['website_links'])) {
    $decoded = json_decode((string)$teacher['website_links'], true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        $existing_pairs = $decoded;
    }
}

$flash_success = null;
$flash_error = null;

/* ===== submit ===== */
if (isset($_POST['update_profile'])) {
    $full_name = trim((string)($_POST['full_name'] ?? ''));
    $email     = trim((string)($_POST['email'] ?? ''));

    $subjects_arr = $_POST['subject_name'] ?? [];
    $links_arr    = $_POST['subject_link'] ?? [];
    $pairs = json_pairs_from_post((array)$subjects_arr, (array)$links_arr);

    $subjects_csv = implode(', ', array_filter(array_map(fn($p)=>$p['subject'], $pairs)));
    $website_links_json = json_encode($pairs, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    /* avatar upload */
    $avatar_rel_path = $teacher['avatar_path'] ?? null;

    if (!empty($_FILES['avatar']['name'])) {
        if ($_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
            $flash_error = "Помилка завантаження файлу (код {$_FILES['avatar']['error']}).";
        } else {
            if ($_FILES['avatar']['size'] > 5 * 1024 * 1024) {
                $flash_error = "Файл завеликий. Максимум 5 МБ.";
            } else {
                $finfo = new finfo(FILEINFO_MIME_TYPE);
                $mime = $finfo->file($_FILES['avatar']['tmp_name']);
                $allowed = [
                    'image/jpeg' => 'jpg',
                    'image/png'  => 'png',
                    'image/webp' => 'webp'
                ];
                if (!isset($allowed[$mime])) {
                    $flash_error = "Непідтримуваний тип зображення. Дозволено: JPG, PNG, WEBP.";
                } else {
                    $safe_dir = sanitize_dirname($full_name ?: (string)$teacher['full_name']);
                    $base_dir = realpath(__DIR__ . '/..');
                    $avatars_dir = $base_dir . '/img/avatars/' . $safe_dir;

                    if (!is_dir($avatars_dir)) {
                        if (!mkdir($avatars_dir, 0775, true)) {
                            $flash_error = "Не вдалося створити каталог для аватарки.";
                        }
                    }

                    if (!$flash_error) {
                        $ext = $allowed[$mime];
                        $filename = 'avatar.' . $ext;
                        $dest = $avatars_dir . '/' . $filename;

                        foreach (['jpg','jpeg','png','webp'] as $old) {
                            $oldPath = $avatars_dir . '/avatar.' . $old;
                            if (is_file($oldPath)) @unlink($oldPath);
                        }

                        if (!move_uploaded_file($_FILES['avatar']['tmp_name'], $dest)) {
                            $flash_error = "Не вдалося зберегти файл аватарки.";
                        } else {
                            $avatar_rel_path = 'img/avatars/' . $safe_dir . '/' . $filename;
                        }
                    }
                }
            }
        }
    }

    if (!$flash_error) {
        $hasAvatarCol = false;
        $chk = $conn->query("SELECT COUNT(*) AS c FROM information_schema.COLUMNS
                             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='users' AND COLUMN_NAME='avatar_path'");
        if ($chk && ($row = $chk->fetch_assoc()) && ((int)($row['c'] ?? 0) > 0)) { $hasAvatarCol = true; }

        if ($hasAvatarCol && $avatar_rel_path) {
            $sql = "UPDATE users SET full_name=?, email=?, subjects=?, website_links=?, avatar_path=? WHERE id=?";
            $stmt = $conn->prepare($sql);
            if (!$stmt) { die("Помилка підготовки запиту: " . $conn->error); }
            $stmt->bind_param("sssssi", $full_name, $email, $subjects_csv, $website_links_json, $avatar_rel_path, $teacher_id);
        } else {
            $sql = "UPDATE users SET full_name=?, email=?, subjects=?, website_links=? WHERE id=?";
            $stmt = $conn->prepare($sql);
            if (!$stmt) { die("Помилка підготовки запиту: " . $conn->error); }
            $stmt->bind_param("ssssi", $full_name, $email, $subjects_csv, $website_links_json, $teacher_id);
        }

        if (!$stmt->execute()) {
            $flash_error = "Помилка оновлення профілю: " . $stmt->error;
        } else {
            $flash_success = "Профіль успішно оновлено!";
            $_SESSION['full_name'] = $full_name;

            $teacher['full_name'] = $full_name;
            $teacher['email'] = $email;
            $teacher['subjects'] = $subjects_csv;
            $teacher['website_links'] = $website_links_json;
            if ($avatar_rel_path) $teacher['avatar_path'] = $avatar_rel_path;

            $existing_pairs = $pairs;
        }
        $stmt->close();
    }
}

$conn->close();

/* ===== підготовка header.php ===== */
$siteName  = 'Розклад занять';
$pageTitle = 'Редагування профілю — ' . (string)($teacher['full_name'] ?? '');
$pageCss   = [
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
    '/css/admin.css?v=4',
    '/css/admin_teacher_profile.css?v=1'
];

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

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

      <h1 class="admin-title mb-3">
        Редагування профілю
        <span class="d-block fs-6 fw-semibold text-muted mt-1"><?= htmlspecialchars((string)$teacher['full_name'], ENT_QUOTES, 'UTF-8'); ?></span>
      </h1>

      <?php if (!empty($flash_success)): ?>
        <div class="alert alert-success text-center"><?= htmlspecialchars((string)$flash_success, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endif; ?>
      <?php if (!empty($flash_error)): ?>
        <div class="alert alert-danger text-center"><?= htmlspecialchars((string)$flash_error, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endif; ?>

      <section class="card-block">
        <form method="POST" enctype="multipart/form-data">
          <!-- ПІБ -->
          <div class="mb-3">
            <label for="full_name" class="form-label">ПІБ:</label>
            <input class="form-control" type="text" id="full_name" name="full_name"
                   value="<?= htmlspecialchars((string)$teacher['full_name'], ENT_QUOTES, 'UTF-8'); ?>" required>
          </div>

          <!-- Email -->
          <div class="mb-3">
            <label for="email" class="form-label">Email (або інший спосіб зв’язку):</label>
            <input class="form-control" type="email" id="email" name="email"
                   value="<?= htmlspecialchars((string)($teacher['email'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>" required>
          </div>

          <!-- Аватарка -->
          <div class="mb-3">
            <label class="form-label">Аватарка (до 5 МБ, JPG/PNG/WEBP):</label>

            <div class="tp-edit-head">
              <img class="tp-avatar" id="avatarPreview"
                   src="<?= !empty($teacher['avatar_path']) ? '../' . htmlspecialchars((string)$teacher['avatar_path'], ENT_QUOTES, 'UTF-8') : 'https://via.placeholder.com/112x112?text=Avatar'; ?>"
                   alt="Avatar">

              <div class="tp-filebox">
                <input class="form-control" type="file" name="avatar" id="avatar" accept="image/*">
                <div class="tp-help mt-1">Файл збережеться у <code>img/avatars/&lt;ПІБ&gt;/avatar.*</code></div>
              </div>
            </div>
          </div>

          <!-- Пари -->
          <div class="mb-3">
            <label class="form-label">Предмети та посилання (Classroom/портал):</label>

            <div id="pairsContainer">
              <?php
              if (empty($existing_pairs)) {
                  $existing_pairs = [['subject'=>'','link'=>'']];
              }
              foreach ($existing_pairs as $p):
              ?>
                <div class="pair-row">
                  <input class="form-control" type="text" name="subject_name[]" placeholder="Назва предмету"
                         value="<?= htmlspecialchars((string)($p['subject'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>">
                  <input class="form-control" type="url" name="subject_link[]" placeholder="Посилання на курс"
                         value="<?= htmlspecialchars((string)($p['link'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>">
                  <button type="button" class="btn btn-outline-danger" onclick="removePair(this)">–</button>
                </div>
              <?php endforeach; ?>
            </div>

            <button type="button" class="btn btn-outline-secondary mt-2" onclick="addPair()">+ Додати</button>
            <div class="tp-help mt-2">
              Зберігається як JSON у <code>website_links</code>. Для сумісності поле <code>subjects</code> отримує список назв.
            </div>
          </div>

          <button class="btn btn-primary w-100 mt-2" type="submit" name="update_profile">Зберегти</button>
        </form>
      </section>

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

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

<script>
const pairsContainer = document.getElementById('pairsContainer');

function addPair() {
  const row = document.createElement('div');
  row.className = 'pair-row';
  row.innerHTML = `
    <input class="form-control" type="text" name="subject_name[]" placeholder="Назва предмету">
    <input class="form-control" type="url" name="subject_link[]" placeholder="Посилання на курс">
    <button type="button" class="btn btn-outline-danger" onclick="removePair(this)">–</button>
  `;
  pairsContainer.appendChild(row);
}

function removePair(btn) {
  const row = btn.closest('.pair-row');
  if (pairsContainer.children.length > 1) row.remove();
  else row.querySelectorAll('input').forEach(i => i.value = '');
}

document.getElementById('avatar')?.addEventListener('change', function(){
  const [file] = this.files;
  if (!file) return;
  if (file.size > 5 * 1024 * 1024) {
    alert('Файл завеликий. Максимум 5 МБ.');
    this.value = '';
    return;
  }
  const img = document.getElementById('avatarPreview');
  img.src = URL.createObjectURL(file);
});
</script>

</body>
</html>
