<?php
require 'config.php';

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // teks biasa
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $fullname = trim($_POST['fullname'] ?? '');
    $nis = trim($_POST['nis'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $class = trim($_POST['class'] ?? '');
    $password = $_POST['password'] ?? '';
    $password2 = $_POST['password2'] ?? '';

    // inisialisasi: belum ada foto
    $photoPath = null; // <-- penting: null jika tidak ada upload

    // validasi awal fields
    if ($username === '' || $email === '' || $fullname === '' || $nis === '' || $class === '' || $password === '') {
        $errors[] = "Semua field wajib diisi (kecuali No Telepon dan Foto).";
    } elseif ($password !== $password2) {
        $errors[] = "Password konfirmasi tidak cocok.";
    } else {
        // cek username/email unik
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        if ($stmt->fetch()) {
            $errors[] = "Username atau Email sudah digunakan.";
        }
    }

    // --- handle photo upload jika ada ---
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] !== UPLOAD_ERR_NO_FILE) {
      $file = $_FILES['photo'];
      $maxSize = 2 * 1024 * 1024; // 2MB
      $allowedMime = ['image/jpeg','image/png','image/webp'];
      $allowedExt = ['jpg','jpeg','png','webp'];

      if ($file['error'] !== UPLOAD_ERR_OK) {
          $errors[] = "Terjadi kesalahan saat upload foto.";
      } elseif ($file['size'] > $maxSize) {
          $errors[] = "Ukuran foto maksimal 2MB.";
      } else {
          $imgInfo = @getimagesize($file['tmp_name']);
          if ($imgInfo === false) {
              $errors[] = "File yang dikirim bukan gambar.";
          } else {
              $mime = $imgInfo['mime'];
              if (!in_array($mime, $allowedMime)) {
                  $errors[] = "Tipe file tidak diperbolehkan. Gunakan JPG, PNG, atau WEBP.";
              } else {
                  $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                  if (!in_array($ext, $allowedExt)) {
                      $map = ['image/jpeg'=>'jpg','image/png'=>'png','image/webp'=>'webp'];
                      $ext = $map[$mime] ?? 'jpg';
                  }

                  // Simpan file di folder uploads yang satu level di atas folder login
                  $uploadsDir = realpath(__DIR__ . '/../uploads');
                  if ($uploadsDir === false) {
                      $uploadsDir = __DIR__ . '/../uploads';
                      if (!is_dir($uploadsDir)) {
                          mkdir($uploadsDir, 0755, true);
                      }
                  }

                  // buat nama file unik
                  $filename = time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
                  $destination = rtrim($uploadsDir, '/\\') . '/' . $filename;

                  if (!move_uploaded_file($file['tmp_name'], $destination)) {
                      $errors[] = "Gagal menyimpan file foto.";
                  } else {
                      // **PENTING**: simpan HANYA nama file ke DB (bukan 'uploads/...')
                      $photoPath = $filename; // <-- hanya nama file
                  }
              }
          }
      }
    }

    // --- jika tidak ada error, simpan user ---
    if (empty($errors)) {
        $hash = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $pdo->prepare("
            INSERT INTO users 
            (username, email, fullname, nis, phone, class, password, photo, role, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'user', NOW())
        ");
        // $photoPath bisa null atau nama file
        $stmt->execute([$username, $email, $fullname, $nis, $phone, $class, $hash, $photoPath]);
        header('Location: login.php?registered=1');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Register - Pustakaia</title>
  <style>
    html, body {
      height: 100%;
      margin: 0;
      display: flex;
      flex-direction: column;
      font-family: "Poppins", Arial, sans-serif;
      background: linear-gradient(135deg, #f9f9f9, #e9f5ec);
      color: #222;
    }
    a { text-decoration: none; color: inherit; }
    header { display: flex; justify-content: space-between; align-items: center; padding: 20px 40px; background: #fff; border-bottom: 1px solid #ddd; }
    header .logo { font-size: 22px; font-weight: bold; color: #069797; }
    main { flex: 1; display: flex; justify-content: center; align-items: center; padding: 40px 20px; }
    .register-container { max-width: 480px; width: 100%; background: #fff; padding: 24px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
    .register-container h2 { text-align: center; margin-bottom: 14px; color: #069797; }
    .msg { font-size: 14px; margin-bottom: 10px; }
    .msg.error { color: red; }
    .input-group { margin-bottom: 12px; }
    .input-group label { font-size: 14px; display: block; margin-bottom: 6px; }
    .input-group input[type="text"],
    .input-group input[type="email"],
    .input-group input[type="password"],
    .input-group input[type="file"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; box-sizing: border-box; }
    .pw-row { display:flex; gap:8px; }
    .pw-row input { flex: 1; }
    .pw-toggle { padding: 10px 12px; border-radius: 6px; background:#eee; border:1px solid #ddd; cursor:pointer; }
    button { width: 100%; padding: 12px; background: #069797; border: none; border-radius: 6px; color: #fff; font-size: 16px; cursor: pointer; transition: 0.3s; }
    button:hover { background: #048080; }
    .login-link { text-align: center; margin-top: 12px; font-size: 14px; }
    .login-link a { color: #069797; font-weight: bold; }
    .preview { margin-top: 8px; max-height: 200px; object-fit: cover; border-radius:6px; border:1px solid #ddd; }
    /* camera modal */
    .camera-wrap { display:none; position:fixed; inset:0; background: rgba(0,0,0,0.6); align-items:center; justify-content:center; z-index:1000; }
    .camera-box { background:#fff; padding:12px; border-radius:8px; max-width:520px; width:92%; }
    .camera-box video { width:100%; border-radius:6px; background:#000; }
    .camera-controls { display:flex; gap:8px; margin-top:8px; justify-content:flex-end; }
    footer { background: #fff; padding: 20px 40px; font-size: 14px; color: #222; border-top: 1px solid #ddd; }
    .pw-wrap {
  position: relative;
}

.pw-wrap input {
  width: 100%;
  padding-right: 40px; /* ruangan untuk ikon mata */
}

.toggle-eye {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

  </style>
</head>
<body>
  <header>
    <div class="logo">📚 Pustakaia</div>
  </header>

  <main>
    <div class="register-container">
      <h2>Register</h2>
      <?php foreach ($errors as $e): ?>
        <p class="msg error"><?= htmlspecialchars($e) ?></p>
      <?php endforeach; ?>

      <!-- enctype penting untuk upload file -->
      <form method="post" enctype="multipart/form-data" id="registerForm">
        <div class="input-group"><label>Username</label><input type="text" name="username" required value="<?= isset($username) ? htmlspecialchars($username) : '' ?>"></div>
        <div class="input-group"><label>Email</label><input type="email" name="email" required value="<?= isset($email) ? htmlspecialchars($email) : '' ?>"></div>
        <div class="input-group"><label>Nama Lengkap</label><input type="text" name="fullname" required value="<?= isset($fullname) ? htmlspecialchars($fullname) : '' ?>"></div>
        <div class="input-group"><label>NIS</label><input type="text" name="nis" required value="<?= isset($nis) ? htmlspecialchars($nis) : '' ?>"></div>
        <div class="input-group"><label>No Telepon</label><input type="text" name="phone" value="<?= isset($phone) ? htmlspecialchars($phone) : '' ?>"></div>
        <div class="input-group"><label>Kelas</label><input type="text" name="class" required placeholder="XI IPA 2" value="<?= isset($class) ? htmlspecialchars($class) : '' ?>"></div>

        <div class="input-group">
  <label>Password</label>
  <div class="pw-wrap">
    <input type="password" id="password" name="password" required>
    <span class="toggle-eye" id="togglePw">
      <!-- ikon mata -->
      <svg id="eyeOpen" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#555" viewBox="0 0 24 24">
        <path d="M12 5c-7.633 0-11 7-11 7s3.367 7 11 7 11-7 11-7-3.367-7-11-7zm0 12a5 5 0 1 1 .001-10.001A5 5 0 0 1 12 17z"/>
      </svg>

      <!-- ikon mata tertutup -->
      <svg id="eyeClosed" style="display:none;" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#555" viewBox="0 0 24 24">
        <path d="M2 12s3.6-7 10-7c1.7 0 3.2.4 4.5 1l1.5-1.5 1.4 1.4-16 16-1.4-1.4 2.4-2.4C3 15 2 12 2 12zm12.2 2.2 2.1-2.1c-.3-2.1-2-3.8-4.1-4.1l-2.1 2.1c1.5.4 2.7 1.6 3.1 3.1z"/>
      </svg>
    </span>
  </div>
</div>

<div class="input-group">
  <label>Ulangi Password</label>
  <div class="pw-wrap">
    <input type="password" id="password2" name="password2" required>
    <span class="toggle-eye" id="togglePw2">
      <svg id="eyeOpen2" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#555" viewBox="0 0 24 24">
        <path d="M12 5c-7.633 0-11 7-11 7s3.367 7 11 7 11-7 11-7-3.367-7-11-7zm0 12a5 5 0 1 1 .001-10.001A5 5 0 0 1 12 17z"/>
      </svg>

      <svg id="eyeClosed2" style="display:none;" xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#555" viewBox="0 0 24 24">
        <path d="M2 12s3.6-7 10-7c1.7 0 3.2.4 4.5 1l1.5-1.5 1.4 1.4-16 16-1.4-1.4 2.4-2.4C3 15 2 12 2 12zm12.2 2.2 2.1-2.1c-.3-2.1-2-3.8-4.1-4.1l-2.1 2.1c1.5.4 2.7 1.6 3.1 3.1z"/>
      </svg>
    </span>
  </div>
</div>


        <div class="input-group">
          <label>Foto (opsional)</label>
          <!-- input file bawaan; accept + capture => pada mobile memberikan pilihan kamera/galeri -->
          <input id="photoInput" type="file" name="photo" accept="image/*" capture="environment">
          <img id="previewImg" class="preview" src="" alt="" style="display:none;">
          <div style="margin-top:8px; display:flex; gap:8px;">
            <button type="button" id="openCamera" style="width:auto;">Ambil Foto Langsung</button>
          </div>
        </div>

        <button type="submit">Register</button>
      </form>

      <div class="login-link">
        Sudah punya akun? <a href="login.php">Login</a>
      </div>
    </div>
  </main>

  <!-- Camera modal untuk capture via getUserMedia (desktop & mobile browser modern) -->
  <div id="cameraModal" class="camera-wrap">
    <div class="camera-box">
      <video id="camVideo" autoplay playsinline></video>
      <div class="camera-controls">
        <button id="btnCapture">Capture</button>
        <button id="btnCloseCam">Close</button>
      </div>
    </div>
  </div>

  <footer>
    <div class="footer-bottom">
      <p>© 2025, Pustakaia | Website developed by Grup 3</p>
      <div class="footer-links">
        <a href="#">Terms of Use</a>
        <a href="#">Privacy Policy</a>
      </div>
    </div>
  </footer>

  <script>
  // Toggle password visibility (kode asli Anda, tidak diubah)
  function initPwToggle(btnId, inputId) {
    const btn = document.getElementById(btnId);
    const input = document.getElementById(inputId);
    btn.addEventListener('click', () => {
      if (input.type === 'password') {
        input.type = 'text';
        btn.textContent = 'Hide';
        btn.setAttribute('aria-pressed', 'true');
      } else {
        input.type = 'password';
        btn.textContent = 'Show';
        btn.setAttribute('aria-pressed', 'false');
      }
    });
  }
  initPwToggle('togglePw', 'password');
  initPwToggle('togglePw2', 'password2');

  // Preview image when user selects file (kode asli Anda, tidak diubah)
  const photoInput = document.getElementById('photoInput');
  const previewImg = document.getElementById('previewImg');
  photoInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (!file) {
      previewImg.style.display = 'none';
      previewImg.src = '';
      return;
    }
    if (!file.type.startsWith('image/')) {
      previewImg.style.display = 'none';
      previewImg.src = '';
      return;
    }
    const reader = new FileReader();
    reader.onload = function(ev) {
      previewImg.src = ev.target.result;
      previewImg.style.display = 'block';
    };
    reader.readAsDataURL(file);
  });

  // Kamera via getUserMedia (diperbaiki dengan debug dan check dukungan)
  const openCameraBtn = document.getElementById('openCamera');
  const cameraModal = document.getElementById('cameraModal');
  const camVideo = document.getElementById('camVideo');
  const btnCloseCam = document.getElementById('btnCloseCam');
  const btnCapture = document.getElementById('btnCapture');
  let stream = null;

  // Check dukungan getUserMedia
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    console.warn('getUserMedia tidak didukung di browser ini.');
    openCameraBtn.disabled = true; // Disable tombol jika tidak didukung
    openCameraBtn.textContent = 'Kamera Tidak Didukung';
  } else {
    openCameraBtn.addEventListener('click', async () => {
      console.log('Tombol Ambil Foto Langsung diklik.'); // Debug log
      try {
        stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
        console.log('Kamera berhasil diakses.'); // Debug log
        camVideo.srcObject = stream;
        cameraModal.style.display = 'flex'; // Pastikan modal muncul
      } catch (err) {
        console.error('Error akses kamera:', err); // Debug log
        alert('Tidak dapat mengakses kamera: ' + err.message + '. Gunakan input foto biasa.');
      }
    });
  }

  btnCloseCam.addEventListener('click', () => {
    console.log('Modal kamera ditutup.'); // Debug log
    cameraModal.style.display = 'none';
    if (stream) {
      stream.getTracks().forEach(t => t.stop());
      stream = null;
    }
  });

  btnCapture.addEventListener('click', () => {
    if (!stream) {
      console.warn('Tidak ada stream kamera untuk capture.');
      return;
    }
    console.log('Capture foto dimulai.'); // Debug log
    const canvas = document.createElement('canvas');
    canvas.width = camVideo.videoWidth || 640;
    canvas.height = camVideo.videoHeight || 480;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(camVideo, 0, 0, canvas.width, canvas.height);
    canvas.toBlob((blob) => {
      const file = new File([blob], 'camera_' + Date.now() + '.png', { type: 'image/png' });
      const url = URL.createObjectURL(file);
      previewImg.src = url;
      previewImg.style.display = 'block';
      try {
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(file);
        photoInput.files = dataTransfer.files;
        console.log('Foto berhasil diset ke input file.'); // Debug log
      } catch (e) {
        console.warn('Tidak bisa set input.files secara programatik di browser ini. Fallback diperlukan.');
      }
      cameraModal.style.display = 'none';
      if (stream) {
        stream.getTracks().forEach(t => t.stop());
        stream = null;
      }
    }, 'image/png', 0.95);
  });

  // Jika ingin: sebelum submit bisa cek ukuran file agar sesuai (client-side quick check)
  document.getElementById('registerForm').addEventListener('submit', function(e){
    const f = photoInput.files[0];
    if (f && f.size > 2 * 1024 * 1024) { // 2MB
      e.preventDefault();
      alert('Ukuran foto maksimal 2MB.');
    }
  });

  // Setup toggle untuk password (kode asli Anda, tidak diubah)
  function setupToggle(eyeOpen, eyeClosed, input) {
    const openIcon = document.getElementById(eyeOpen);
    const closedIcon = document.getElementById(eyeClosed);
    const inputField = document.getElementById(input);
    openIcon.parentElement.addEventListener('click', () => {
      if (inputField.type === "password") {
        inputField.type = "text";
        openIcon.style.display = "none";
        closedIcon.style.display = "block";
      } else {
        inputField.type = "password";
        openIcon.style.display = "block";
        closedIcon.style.display = "none";
      }
    });
  }
  setupToggle('eyeOpen', 'eyeClosed', 'password');
  setupToggle('eyeOpen2', 'eyeClosed2', 'password2');
</script>
