<?php
session_start();
require_once 'db.php';

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $nama = trim($_POST['nama']);
    $jenis_kelamin = $_POST['jenis_kelamin'] ?? null;
    $tempat_lahir = $_POST['tempat_lahir'] ?? null;
    $tanggal_lahir = $_POST['tanggal_lahir'] ?? null;
    $nisn = $_POST['nisn'] ?? null;

    // Validasi
    if (empty($username) || empty($password) || empty($confirm_password) || empty($nama)) {
        $error = "Semua field wajib diisi!";
    } elseif ($password !== $confirm_password) {
        $error = "Password tidak cocok!";
    } elseif (strlen($password) < 6) {
        $error = "Password minimal 6 karakter!";
    } else {
        try {
            // Cek username sudah ada
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $error = "Username sudah digunakan!";
            } else {
                // Mulai transaction
                $pdo->beginTransaction();

                // Insert ke tabel siswa
                $stmt_siswa = $pdo->prepare("INSERT INTO siswa (nama, jenis_kelamin, tempat_lahir, tanggal_lahir, nisn, kelas_id) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt_siswa->execute([$nama, $jenis_kelamin, $tempat_lahir, $tanggal_lahir, $nisn, 4]); // Default kelas_id 4
                $siswa_id = $pdo->lastInsertId();

                // Insert ke tabel users
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt_user = $pdo->prepare("INSERT INTO users (username, password, siswa_id, role) VALUES (?, ?, ?, 'siswa')");
                $stmt_user->execute([$username, $hashed_password, $siswa_id]);

                $pdo->commit();
                
                $success = "Pendaftaran berhasil! Silakan login.";
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Terjadi kesalahan: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daftar Akun Siswa</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gradient-to-br from-blue-500 to-purple-600 min-h-screen flex items-center justify-center p-4">
    <div class="bg-white p-8 rounded-2xl shadow-2xl w-full max-w-md">
        <div class="text-center mb-6">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-blue-100 rounded-full mb-4">
                <i class="fas fa-user-graduate text-blue-600 text-2xl"></i>
            </div>
            <h2 class="text-3xl font-bold text-gray-900">Daftar Akun Siswa</h2>
            <p class="text-gray-600">Isi data diri untuk membuat akun</p>
        </div>

        <?php if ($error): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-4 text-sm">
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4 text-sm">
                <?= htmlspecialchars($success) ?>
                <a href="login_siswa.php" class="block mt-2 text-blue-600 hover:underline">Login di sini</a>
            </div>
        <?php endif; ?>

        <form method="POST" class="space-y-4">
            <!-- Data Login -->
            <div class="border-b border-gray-200 pb-4">
                <h3 class="text-lg font-semibold text-gray-800 mb-3">Data Login</h3>
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700">Username *</label>
                    <input type="text" id="username" name="username" required 
                           class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                           value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
                </div>
                <div class="grid grid-cols-2 gap-4 mt-3">
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700">Password *</label>
                        <input type="password" id="password" name="password" required 
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label for="confirm_password" class="block text-sm font-medium text-gray-700">Konfirmasi Password *</label>
                        <input type="password" id="confirm_password" name="confirm_password" required 
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
            </div>

            <!-- Data Pribadi -->
            <div>
                <h3 class="text-lg font-semibold text-gray-800 mb-3">Data Pribadi</h3>
                <div>
                    <label for="nama" class="block text-sm font-medium text-gray-700">Nama Lengkap *</label>
                    <input type="text" id="nama" name="nama" required 
                           class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                           value="<?= htmlspecialchars($_POST['nama'] ?? '') ?>">
                </div>
                
                <div class="grid grid-cols-2 gap-4 mt-3">
                    <div>
                        <label for="jenis_kelamin" class="block text-sm font-medium text-gray-700">Jenis Kelamin</label>
                        <select id="jenis_kelamin" name="jenis_kelamin" 
                                class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                            <option value="">Pilih</option>
                            <option value="L" <?= ($_POST['jenis_kelamin'] ?? '') == 'L' ? 'selected' : '' ?>>Laki-laki</option>
                            <option value="P" <?= ($_POST['jenis_kelamin'] ?? '') == 'P' ? 'selected' : '' ?>>Perempuan</option>
                        </select>
                    </div>

                    <div>
                        <label for="nisn" class="block text-sm font-medium text-gray-700">NISN</label>
                        <input type="text" id="nisn" name="nisn" 
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                               value="<?= htmlspecialchars($_POST['nisn'] ?? '') ?>">
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4 mt-3">
                    <div>
                        <label for="tempat_lahir" class="block text-sm font-medium text-gray-700">Tempat Lahir</label>
                        <input type="text" id="tempat_lahir" name="tempat_lahir" 
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                               value="<?= htmlspecialchars($_POST['tempat_lahir'] ?? '') ?>">
                    </div>

                    <div>
                        <label for="tanggal_lahir" class="block text-sm font-medium text-gray-700">Tanggal Lahir</label>
                        <input type="date" id="tanggal_lahir" name="tanggal_lahir" 
                               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                               value="<?= htmlspecialchars($_POST['tanggal_lahir'] ?? '') ?>">
                    </div>
                </div>
            </div>

            <button type="submit" class="w-full bg-blue-600 text-white py-3 px-4 rounded-md hover:bg-blue-700 transition font-semibold text-lg">
                <i class="fas fa-user-plus mr-2"></i> Daftar Sekarang
            </button>
        </form>

        <div class="mt-6 text-center">
            <p class="text-gray-600">Sudah punya akun? 
                <a href="login_siswa.php" class="text-blue-600 hover:underline font-semibold">Login di sini</a>
            </p>
        </div>
    </div>
</body>
</html>