<?php
/**
 * Registration Page
 * High security registration with comprehensive validation
 */
require_once __DIR__ . '/auth/functions.php';

// Redirect if already logged in
if (isLoggedIn()) {
    $role = getUserRole();
    if ($role === 'admin') {
        header('Location: /muanjai/admin/dashboard.php');
    } else {
        header('Location: /muanjai/user/dashboard.php');
    }
    exit;
}

$errors = [];
$formData = [
    'name' => '',
    'username' => '',
    'email' => ''
];

// Process registration form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
        $errors[] = 'ຄຳຂໍບໍ່ຖືກຕ້ອງ ກະລຸນາລອງໃໝ່';
    } else {
        $name = $_POST['name'] ?? '';
        $username = $_POST['username'] ?? '';
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        // Store form data for re-population
        $formData['name'] = $name;
        $formData['username'] = $username;
        $formData['email'] = $email;

        // Validate name
        if (empty($name)) {
            $errors[] = 'ກະລຸນາໃສ່ຊື່-ນາມສະກຸນ';
        }

        // Check password confirmation
        if ($password !== $confirmPassword) {
            $errors[] = 'ລະຫັດຜ່ານ ແລະ ຢືນຢັນລະຫັດຜ່ານບໍ່ກົງກັນ';
        }

        if (empty($errors)) {
            $result = registerUser($pdo, $name, $username, $email, $password);

            if ($result['success']) {
                regenerateCSRFToken();
                header('Location: /muanjai/login.php?registered=1');
                exit;
            } else {
                $errors = $result['errors'];
            }
        }
    }
}

$csrfToken = generateCSRFToken();
?>
<!DOCTYPE html>
<html lang="lo">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="ລົງທະບຽນ - Muanjai">
    <title>ລົງທະບຽນ | Muanjai</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@300;400;500;600;700&display=swap"
        rel="stylesheet">
    <link rel="icon" type="image/png" href="img/logo/muanjai_logo.png">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Noto Sans Lao', sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f0f23 100%);
            padding: 20px;
        }

        .register-container {
            width: 100%;
            max-width: 480px;
        }

        .register-card {
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(20px);
            border-radius: 24px;
            padding: 48px 40px;
            border: 1px solid rgba(193, 153, 42, 0.2);
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
        }

        .logo {
            text-align: center;
            margin-bottom: 32px;
        }

        .logo-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #c1992a 0%, #e8c547 100%);
            border-radius: 20px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
            box-shadow: 0 10px 40px rgba(193, 153, 42, 0.3);
        }

        .logo-icon svg {
            width: 40px;
            height: 40px;
            fill: #ffffff;
        }

        .logo h1 {
            color: #ffffff;
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .logo p {
            color: rgba(255, 255, 255, 0.6);
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            color: rgba(255, 255, 255, 0.8);
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
        }

        .input-wrapper {
            position: relative;
        }

        .input-wrapper svg {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            width: 20px;
            height: 20px;
            fill: rgba(255, 255, 255, 0.4);
            transition: fill 0.3s ease;
        }

        .form-group input {
            width: 100%;
            padding: 14px 14px 14px 48px;
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 12px;
            font-size: 16px;
            color: #ffffff;
            font-family: 'Noto Sans Lao', sans-serif;
            transition: all 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: #c1992a;
            background: rgba(255, 255, 255, 0.1);
            box-shadow: 0 0 0 4px rgba(193, 153, 42, 0.15);
        }

        .form-group input:focus+svg,
        .input-wrapper:focus-within svg {
            fill: #c1992a;
        }

        .form-group input::placeholder {
            color: rgba(255, 255, 255, 0.4);
        }

        .form-group input.valid {
            border-color: #22c55e;
        }

        .form-group input.invalid {
            border-color: #ef4444;
        }

        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 24px;
            font-size: 14px;
        }

        .alert-error {
            background: rgba(239, 68, 68, 0.15);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #fca5a5;
        }

        .alert-error ul {
            margin: 8px 0 0 20px;
            padding: 0;
        }

        .alert-error li {
            margin-bottom: 4px;
        }

        .password-requirements {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 20px;
        }

        .password-requirements h4 {
            color: rgba(255, 255, 255, 0.8);
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 12px;
        }

        .requirement {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
            color: rgba(255, 255, 255, 0.5);
            margin-bottom: 6px;
            transition: color 0.3s ease;
        }

        .requirement.valid {
            color: #22c55e;
        }

        .requirement svg {
            width: 16px;
            height: 16px;
            fill: currentColor;
        }

        .btn-register {
            width: 100%;
            padding: 16px;
            background: linear-gradient(135deg, #c1992a 0%, #e8c547 100%);
            border: none;
            border-radius: 12px;
            color: #ffffff;
            font-size: 16px;
            font-weight: 600;
            font-family: 'Noto Sans Lao', sans-serif;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(193, 153, 42, 0.3);
        }

        .btn-register:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(193, 153, 42, 0.4);
        }

        .btn-register:active {
            transform: translateY(0);
        }

        .btn-register:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .login-link {
            text-align: center;
            margin-top: 24px;
            color: rgba(255, 255, 255, 0.6);
            font-size: 14px;
        }

        .login-link a {
            color: #c1992a;
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .login-link a:hover {
            color: #e8c547;
        }

        .password-strength {
            height: 4px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 2px;
            margin-top: 8px;
            overflow: hidden;
        }

        .password-strength-bar {
            height: 100%;
            width: 0%;
            transition: all 0.3s ease;
            border-radius: 2px;
        }

        .strength-weak {
            background: #ef4444;
            width: 25%;
        }

        .strength-fair {
            background: #f97316;
            width: 50%;
        }

        .strength-good {
            background: #eab308;
            width: 75%;
        }

        .strength-strong {
            background: #22c55e;
            width: 100%;
        }

        @media (max-width: 480px) {
            .register-card {
                padding: 32px 24px;
            }

            .logo h1 {
                font-size: 24px;
            }
        }
    </style>
</head>

<body>
    <div class="register-container">
        <div class="register-card">
            <div class="logo">
                <div class="logo-icon">
                    <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path
                            d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
                    </svg>
                </div>
                <h1>ລົງທະບຽນ</h1>
                <p>ສ້າງບັນຊີໃໝ່ເພື່ອເລີ່ມຕົ້ນໃຊ້ງານ</p>
            </div>

            <?php if (!empty($errors)): ?>
                <div class="alert alert-error">
                    <strong>ພົບຂໍ້ຜິດພາດ:</strong>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                            <li>
                                <?= e($error) ?>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form method="POST" action="" id="registerForm">
                <input type="hidden" name="csrf_token" value="<?= e($csrfToken) ?>">

                <div class="form-group">
                    <label for="name">ຊື່-ນາມສະກຸນ</label>
                    <div class="input-wrapper">
                        <input type="text" id="name" name="name" placeholder="ຊື່ ແລະ ນາມສະກຸນ" required
                            autocomplete="name" value="<?= e($formData['name']) ?>">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
                        </svg>
                    </div>
                </div>

                <div class="form-group">
                    <label for="username">ຊື່ຜູ້ໃຊ້</label>
                    <div class="input-wrapper">
                        <input type="text" id="username" name="username"
                            placeholder="username (ຕົວອັກສອນພາສາອັງກິດ, ຕົວເລກ, _)" required autocomplete="username"
                            pattern="^[a-zA-Z0-9_]{3,50}$" value="<?= e($formData['username']) ?>">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
                        </svg>
                    </div>
                </div>

                <div class="form-group">
                    <label for="email">ອີເມວ</label>
                    <div class="input-wrapper">
                        <input type="email" id="email" name="email" placeholder="email@example.com" required
                            autocomplete="email" value="<?= e($formData['email']) ?>">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z" />
                        </svg>
                    </div>
                </div>

                <div class="form-group">
                    <label for="password">ລະຫັດຜ່ານ</label>
                    <div class="input-wrapper">
                        <input type="password" id="password" name="password" placeholder="••••••••" required
                            autocomplete="new-password">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z" />
                        </svg>
                    </div>
                    <div class="password-strength">
                        <div class="password-strength-bar" id="strengthBar"></div>
                    </div>
                </div>

                <div class="password-requirements">
                    <h4>ຂໍ້ກຳນົດລະຫັດຜ່ານ:</h4>
                    <div class="requirement" id="req-length">
                        <svg viewBox="0 0 24 24">
                            <circle cx="12" cy="12" r="10" />
                        </svg>
                        ຢ່າງນ້ອຍ 8 ຕົວອັກສອນ
                    </div>
                    <div class="requirement" id="req-lowercase">
                        <svg viewBox="0 0 24 24">
                            <circle cx="12" cy="12" r="10" />
                        </svg>
                        ມີຕົວພິມນ້ອຍ (a-z)
                    </div>
                    <div class="requirement" id="req-uppercase">
                        <svg viewBox="0 0 24 24">
                            <circle cx="12" cy="12" r="10" />
                        </svg>
                        ມີຕົວພິມໃຫຍ່ (A-Z)
                    </div>
                    <div class="requirement" id="req-number">
                        <svg viewBox="0 0 24 24">
                            <circle cx="12" cy="12" r="10" />
                        </svg>
                        ມີຕົວເລກ (0-9)
                    </div>
                    <div class="requirement" id="req-special">
                        <svg viewBox="0 0 24 24">
                            <circle cx="12" cy="12" r="10" />
                        </svg>
                        ມີສັນຍາລັກພິເສດ (!@#$%...)
                    </div>
                </div>

                <div class="form-group">
                    <label for="confirm_password">ຢືນຢັນລະຫັດຜ່ານ</label>
                    <div class="input-wrapper">
                        <input type="password" id="confirm_password" name="confirm_password" placeholder="••••••••"
                            required autocomplete="new-password">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z" />
                        </svg>
                    </div>
                </div>

                <button type="submit" class="btn-register" id="submitBtn">ລົງທະບຽນ</button>
            </form>

            <div class="login-link">
                ມີບັນຊີຢູ່ແລ້ວ? <a href="login.php">ເຂົ້າສູ່ລະບົບ</a>
            </div>
        </div>
    </div>

    <script>
        const passwordInput = document.getElementById('password');
        const confirmInput = document.getElementById('confirm_password');
        const strengthBar = document.getElementById('strengthBar');
        const submitBtn = document.getElementById('submitBtn');

        const requirements = {
            length: document.getElementById('req-length'),
            lowercase: document.getElementById('req-lowercase'),
            uppercase: document.getElementById('req-uppercase'),
            number: document.getElementById('req-number'),
            special: document.getElementById('req-special')
        };

        const checkIcon = '<svg viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>';
        const circleIcon = '<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/></svg>';

        function validatePassword(password) {
            const checks = {
                length: password.length >= 8,
                lowercase: /[a-z]/.test(password),
                uppercase: /[A-Z]/.test(password),
                number: /[0-9]/.test(password),
                special: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)
            };

            let score = 0;
            Object.keys(checks).forEach(key => {
                const req = requirements[key];
                if (checks[key]) {
                    req.classList.add('valid');
                    req.querySelector('svg').outerHTML = checkIcon;
                    score++;
                } else {
                    req.classList.remove('valid');
                    req.querySelector('svg').outerHTML = circleIcon;
                }
            });

            // Update strength bar
            strengthBar.className = 'password-strength-bar';
            if (score === 0) {
                strengthBar.style.width = '0%';
            } else if (score <= 2) {
                strengthBar.classList.add('strength-weak');
            } else if (score === 3) {
                strengthBar.classList.add('strength-fair');
            } else if (score === 4) {
                strengthBar.classList.add('strength-good');
            } else {
                strengthBar.classList.add('strength-strong');
            }

            return score === 5;
        }

        function validateConfirmPassword() {
            const isMatch = passwordInput.value === confirmInput.value && confirmInput.value.length > 0;

            if (confirmInput.value.length > 0) {
                confirmInput.classList.toggle('valid', isMatch);
                confirmInput.classList.toggle('invalid', !isMatch);
            } else {
                confirmInput.classList.remove('valid', 'invalid');
            }

            return isMatch;
        }

        passwordInput.addEventListener('input', function () {
            validatePassword(this.value);
            if (confirmInput.value.length > 0) {
                validateConfirmPassword();
            }
        });

        confirmInput.addEventListener('input', validateConfirmPassword);

        document.getElementById('registerForm').addEventListener('submit', function (e) {
            const password = passwordInput.value;
            const isPasswordValid = validatePassword(password);
            const isConfirmValid = validateConfirmPassword();

            if (!isPasswordValid) {
                e.preventDefault();
                alert('ລະຫັດຜ່ານບໍ່ຜ່ານເກນທີ່ກຳນົດ ກະລຸນາກວດສອບຂໍ້ກຳນົດລະຫັດຜ່ານ');
                return;
            }

            if (!isConfirmValid) {
                e.preventDefault();
                alert('ລະຫັດຜ່ານ ແລະ ຢືນຢັນລະຫັດຜ່ານບໍ່ກົງກັນ');
                return;
            }
        });
    </script>
</body>

</html>