<?php
// Filename: register.php
require 'config.php';

// 1. CHECK IF REGISTRATION IS ENABLED
if (getSetting('teacher_registration', '0') !== '1') {
    die("<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width,initial-scale=1.0'><title>Closed</title><link href='https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap' rel='stylesheet'><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'><style>body{font-family:'Plus Jakarta Sans',sans-serif;background:#f8f9fd;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;}.card{border:none;border-radius:24px;box-shadow:0 10px 30px rgba(0,0,0,0.05);padding:40px;text-align:center;max-width:350px;width:90%;}.icon{font-size:3rem;color:#cbd5e1;margin-bottom:15px;}</style></head><body><div class='card'><div class='icon'>&times;</div><h4 class='fw-bold text-dark'>Registration Closed</h4><p class='text-muted small mb-4'>Please contact the administrator to create an account.</p><a href='index.php' class='btn btn-dark rounded-pill w-100 fw-bold'>Back to Login</a></div></body></html>");
}

$s_name = getSetting('school_name', 'SAS');
$s_logo = getSetting('school_logo', '');
$msg = ''; $msg_type = '';

// 2. HANDLE FORM SUBMISSION
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // --- FIX APPLIED HERE: Added (?? '') to prevent Undefined Array Key errors ---
    $name    = strtoupper(trim($_POST['full_name'] ?? '')); 
    $ic      = preg_replace('/[^0-9]/', '', $_POST['username'] ?? ''); // Digits only
    $phone   = trim($_POST['phone'] ?? '');
    $pass    = $_POST['password'] ?? '';
    $cpass   = $_POST['confirm_password'] ?? '';
    $captcha = $_POST['captcha'] ?? '';
    $tg_id   = trim($_POST['telegram_chat_id'] ?? ''); 
    
    // --- NEW: ROLE SELECTION LOGIC ---
    $role_input = $_POST['role_type'] ?? 'teacher';
    // Security: Only allow 'teacher' or 'akp' to prevent injection of 'admin' role
    $final_role = ($role_input === 'akp') ? 'akp' : 'teacher';

    // VALIDATION
    if (strlen($ic) !== 12) {
        $msg = "IC Number must be 12 digits."; $msg_type = "danger";
    } elseif (!isset($_SESSION['captcha_code']) || $captcha != $_SESSION['captcha_code']) {
        // Added !isset check for extra safety
        $msg = "Incorrect security code."; $msg_type = "danger";
    } elseif ($pass !== $cpass) {
        $msg = "Passwords do not match."; $msg_type = "danger";
    } else {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->execute([$ic]);
        if ($stmt->fetch()) {
            $msg = "User already exists."; $msg_type = "warning";
        } else {
            try {
                $hashed = password_hash($pass, PASSWORD_BCRYPT);
                // Updated query to use $final_role instead of hardcoded 'teacher'
                $sql = "INSERT INTO users (username, password, full_name, phone_number, telegram_chat_id, role) VALUES (?, ?, ?, ?, ?, ?)";
                $pdo->prepare($sql)->execute([$ic, $hashed, $name, $phone, $tg_id, $final_role]);
                
                $msg = "Account created! Redirecting..."; $msg_type = "success";
                echo "<script>setTimeout(function(){ window.location.href = 'index.php'; }, 1500);</script>";
            } catch (Exception $e) {
                $msg = "Error: " . $e->getMessage(); $msg_type = "danger";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Register - <?= htmlspecialchars($s_name) ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        :root {
            --primary-grad: linear-gradient(135deg, #8B5CF6 0%, #6366f1 100%);
            --bg-color: #f8f9fd;
            --text-dark: #1e293b;
            --text-gray: #64748b;
        }
        body { 
            font-family: 'Plus Jakarta Sans', sans-serif; 
            background-color: var(--bg-color); 
            min-height: 100vh;
            display: flex; flex-direction: column;
            margin: 0;
        }

        /* 1. CURVED HEADER */
        .app-header {
            background: var(--primary-grad);
            padding: 30px 20px 100px 20px; /* Extra bottom padding for overlap */
            border-radius: 0 0 35px 35px;
            color: white;
            text-align: center;
            flex-shrink: 0;
        }
        
        /* UPDATED LOGO STYLE (Matches Index.php) */
        .logo-box {
            margin-bottom: 15px;
            display: flex; align-items: center; justify-content: center;
        }
        .logo-box img { width: 75px; height: 75px; object-fit: contain; }
        .logo-box i { font-size: 75px; color: white; }

        /* 2. FLOATING CARD */
        .content-wrapper {
            flex-grow: 1; display: flex; flex-direction: column; align-items: center;
            margin-top: -80px; padding: 0 20px 40px 20px;
            position: relative; z-index: 10;
        }

        .reg-card {
            background: white; width: 100%; max-width: 400px;
            border-radius: 24px; padding: 25px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.08);
        }

        /* FORM ELEMENTS */
        .form-label { font-size: 0.7rem; font-weight: 700; color: var(--text-gray); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
        
        .form-control { 
            border-radius: 12px; padding: 12px; border: 1px solid #e2e8f0; 
            background-color: #f8fafc; font-size: 0.9rem; color: var(--text-dark);
        }
        .form-control:focus { 
            background-color: white; border-color: #8B5CF6; 
            box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1); 
        }

        .input-group-text {
            background-color: #f8fafc; border: 1px solid #e2e8f0; border-left: 0;
            border-radius: 0 12px 12px 0; color: #94a3b8; cursor: pointer;
        }
        
        /* Specific fix for input group rounded corners */
        .input-group .form-control { border-right: 0; }
        .input-group .form-control:focus { border-color: #8B5CF6; z-index: 2; }

        .btn-primary {
            background: var(--primary-grad); border: none; width: 100%;
            padding: 14px; border-radius: 16px; color: white; font-weight: 700;
            font-size: 1rem; box-shadow: 0 10px 20px rgba(99, 102, 241, 0.2);
            transition: transform 0.2s;
        }
        .btn-primary:active { transform: scale(0.98); opacity: 0.9; }

        .captcha-img { height: 48px; border-radius: 12px; cursor: pointer; width: 100%; object-fit: cover; border: 1px solid #e2e8f0; }

        /* Custom Radio Button Styling */
        .btn-check:checked + .btn-outline-primary {
            background-color: #8B5CF6;
            color: white;
            border-color: #8B5CF6;
        }
        .btn-outline-primary {
            color: #8B5CF6;
            border-color: #8B5CF6;
        }
        .btn-outline-primary:hover {
            background-color: #f3e8ff;
            color: #8B5CF6;
            border-color: #8B5CF6;
        }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="logo-box">
            <?php if($s_logo && file_exists($s_logo)): ?>
                <img src="<?= $s_logo ?>" alt="Logo">
            <?php else: ?>
                <i class="bi bi-person-plus-fill"></i>
            <?php endif; ?>
        </div>
        <h4 class="fw-bold mb-0">Registration</h4>
        <div class="opacity-75 small"><?= htmlspecialchars($s_name) ?></div>
    </div>

    <div class="content-wrapper">
        <div class="reg-card">
            
            <?php if($msg): ?>
                <div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-4 fw-bold">
                    <?= $msg ?>
                </div>
            <?php endif; ?>

            <?php if ($msg_type !== 'success'): ?>
            <form method="POST" onsubmit="showLoading()">
                
                <div class="mb-3">
                    <label class="form-label">Register As</label>
                    <div class="row g-2">
                        <div class="col-6">
                            <input type="radio" class="btn-check" name="role_type" id="roleTeacher" value="teacher" checked>
                            <label class="btn btn-outline-primary w-100 fw-bold py-2 rounded-4" for="roleTeacher">
                                Teacher
                            </label>
                        </div>
                        <div class="col-6">
                            <input type="radio" class="btn-check" name="role_type" id="roleAKP" value="akp">
                            <label class="btn btn-outline-primary w-100 fw-bold py-2 rounded-4" for="roleAKP">
                                AKP Staff
                            </label>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">Full Name</label>
                    <input type="text" name="full_name" class="form-control" placeholder="e.g. Ahmad bin Ali" required autocomplete="name">
                </div>

                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label">IC Number</label>
                        <input type="text" name="username" class="form-control" placeholder="900101..." required maxlength="12" inputmode="numeric" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 12);">
                    </div>
                    <div class="col-6">
                        <label class="form-label">Phone</label>
                        <input type="tel" name="phone" class="form-control" placeholder="012..." required>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label text-primary">Telegram ID (Optional)</label>
                    <div class="input-group">
                        <input type="text" name="telegram_chat_id" class="form-control" placeholder="Numeric ID" inputmode="numeric">
                        <a href="https://t.me/userinfobot" target="_blank" class="input-group-text text-primary bg-white border-start-0" title="Get ID"><i class="bi bi-question-circle-fill"></i></a>
                    </div>
                </div>

                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label">Password</label>
                        <div class="input-group">
                            <input type="password" name="password" id="regPass" class="form-control" required>
                            <span class="input-group-text bg-white" onclick="togglePw('regPass', 'iconReg')"><i class="bi bi-eye-slash" id="iconReg"></i></span>
                        </div>
                    </div>
                    <div class="col-6">
                        <label class="form-label">Confirm</label>
                        <div class="input-group">
                            <input type="password" name="confirm_password" id="confPass" class="form-control" required>
                            <span class="input-group-text bg-white" onclick="togglePw('confPass', 'iconConf')"><i class="bi bi-eye-slash" id="iconConf"></i></span>
                        </div>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="form-label">Security Check</label>
                    <div class="row g-2 align-items-center">
                        <div class="col-5">
                            <img src="captcha.php" class="captcha-img shadow-sm" onclick="this.src='captcha.php?'+Math.random()" title="Tap to refresh">
                        </div>
                        <div class="col-7">
                            <input type="text" name="captcha" class="form-control text-center fw-bold" placeholder="Enter Code" required autocomplete="off" style="height: 48px; letter-spacing: 2px;">
                        </div>
                    </div>
                </div>

                <button type="submit" id="submitBtn" class="btn btn-primary mb-3">
                    Create Account
                </button>

                <div class="text-center">
                    <a href="index.php" class="text-decoration-none small fw-bold text-secondary">Back to Login</a>
                </div>

            </form>
            <?php else: ?>
                <div class="text-center py-5">
                    <div class="spinner-border text-primary mb-3" role="status"></div>
                    <p class="text-muted small fw-bold">Redirecting to login...</p>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="text-center mt-4 text-muted small opacity-50">
            &copy; <?= date('Y') ?> School Attendance System
        </div>
    </div>

    <script>
        function togglePw(inputId, iconId) {
            const input = document.getElementById(inputId);
            const icon = document.getElementById(iconId);
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.replace('bi-eye-slash', 'bi-eye');
            } else {
                input.type = 'password';
                icon.classList.replace('bi-eye', 'bi-eye-slash');
            }
        }

        function showLoading() {
            const btn = document.getElementById('submitBtn');
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Creating...';
            btn.disabled = true;
        }
    </script>
</body>
</html>