<?php
// Mark as returning visitor so next time they see Login page
$cookie_value = '1';
$cookie_expiry = time() + (365 * 24 * 60 * 60); // 1 year
setcookie('nroi_returning_visitor', $cookie_value, $cookie_expiry, '/');
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Account - NROI Portal</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="assets/css/loader.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="icon" type="image/png" href="assets/images/nroi_logo.png">
</head>

<body>
    <?php include 'includes/loader.php'; ?>

    <div class="floating-logo-container left">
        <img src="assets/images/nroi_logo.png" alt="NROI Logo" class="logo-img-floating">
    </div>
    <div class="floating-logo-container right">
        <img src="assets/images/ppsa_logo.png" alt="PPSA Logo" class="logo-img-floating">
    </div>

    <div class="container" style="max-width: 560px;">
        <div class="mobile-logos" style="display:none;">
            <img src="assets/images/nroi_logo.png" alt="NROI Logo" class="mobile-logo-img">
            <img src="assets/images/ppsa_logo.png" alt="PPSA Logo" class="mobile-logo-img">
        </div>

        <h2><b>National Range Officers Institute</b></h2>
        <div class="subtitle">Create Account</div>

        <div id="regIndicator" class="login-indicator" style="display: none;">
            <i id="regIndicatorIcon" class="fas fa-info-circle"></i>
            <span id="regIndicatorMessage"></span>
        </div>

        <form id="createAccountForm">
            <div class="form-group">
                <label>First Name <span style="color: #ef4444;">*</span></label>
                <input type="text" name="first_name" required placeholder="First name">
            </div>
            <div class="form-group">
                <label>Last Name <span style="color: #ef4444;">*</span></label>
                <input type="text" name="last_name" required placeholder="Last name">
            </div>
            <div class="form-group">
                <label>Middle Name</label>
                <input type="text" name="middle_name" placeholder="Middle name (optional)">
            </div>
            <div class="form-group">
                <label>NROI ID <span style="color: #ef4444;">*</span></label>
                <input type="text" name="nroi_id" required placeholder="Enter NROI ID">
            </div>
            <div class="form-group">
                <label>Area <span style="color: #ef4444;">*</span></label>
                <select name="area" id="areaSelect" required>
                    <option value="">Select area</option>
                </select>
            </div>
            <div class="form-group">
                <label>Email <span style="color: #ef4444;">*</span></label>
                <input type="email" name="email" required placeholder="Email address">
            </div>
            <div class="form-group">
                <label>Phone Number <span style="color: #ef4444;">*</span></label>
                <input type="text" name="phone_number" required placeholder="09xxxxxxxxx">
            </div>
            <div class="form-group">
                <label>Password <span style="color: #ef4444;">*</span></label>
                <div class="password-wrapper">
                    <input type="password" name="password" id="regPassword" required placeholder="Create password">
                    <i class="fas fa-eye toggle-password" id="toggleRegPassword"></i>
                </div>
            </div>
            <div class="form-group" style="margin-bottom: 20px;">
                <label>Confirm Password <span style="color: #ef4444;">*</span></label>
                <div class="password-wrapper">
                    <input type="password" name="confirm_password" id="regConfirmPassword" required
                        placeholder="Confirm password">
                    <i class="fas fa-eye toggle-password" id="toggleRegConfirm"></i>
                </div>
            </div>
            <input type="hidden" name="is_active_nroi_member" value="yes">

            <button type="submit" class="btn-primary" id="regSubmitBtn">Create Account</button>

            <p style="text-align: center; margin-top: 24px;">
                <a href="index.php"
                    style="color: var(--primary-color); text-decoration: none; font-size: 0.9rem;">Already have an
                    account? Log in</a>
            </p>
        </form>
    </div>

    <script src="assets/js/loader.js"></script>
    <script>
        (function () {
            const base = (window.location.origin + window.location.pathname).replace(/\/?register\.php\/?$/, '').replace(/\/?index\.php\/?$/, '');
            const apiBase = base + (base.endsWith('/') ? '' : '/');

            // Load areas
            fetch(apiBase + 'api/get_areas.php')
                .then(r => r.json())
                .then(data => {
                    const sel = document.getElementById('areaSelect');
                    if (data.data && data.data.length) {
                        data.data.forEach(function (a) {
                            const opt = document.createElement('option');
                            opt.value = a.area_name;
                            opt.textContent = a.area_name;
                            sel.appendChild(opt);
                        });
                    }
                })
                .catch(function () {
                    document.getElementById('areaSelect').innerHTML = '<option value="">Failed to load areas</option>';
                });

            // Toggle password visibility
            function setupToggle(btnId, inputId) {
                const btn = document.getElementById(btnId);
                const input = document.getElementById(inputId);
                if (!btn || !input) return;
                btn.addEventListener('click', function () {
                    const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
                    input.setAttribute('type', type);
                    this.classList.toggle('fa-eye');
                    this.classList.toggle('fa-eye-slash');
                });
            }
            setupToggle('toggleRegPassword', 'regPassword');
            setupToggle('toggleRegConfirm', 'regConfirmPassword');

            // Submit
            document.getElementById('createAccountForm').addEventListener('submit', function (e) {
                e.preventDefault();
                const form = this;
                const formData = new FormData(form);
                const btn = document.getElementById('regSubmitBtn');
                const indicator = document.getElementById('regIndicator');
                const icon = document.getElementById('regIndicatorIcon');
                const msg = document.getElementById('regIndicatorMessage');

                if (formData.get('password') !== formData.get('confirm_password')) {
                    indicator.style.display = 'flex';
                    indicator.className = 'login-indicator indicator-error';
                    icon.className = 'fas fa-exclamation-circle';
                    msg.textContent = 'Passwords do not match.';
                    return;
                }

                indicator.style.display = 'none';
                btn.disabled = true;
                btn.textContent = 'Creating...';

                fetch(apiBase + 'api/register.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(function (r) { return r.json(); })
                    .then(function (data) {
                        btn.disabled = false;
                        btn.textContent = 'Create Account';
                        indicator.style.display = 'flex';
                        if (data.success) {
                            indicator.className = 'login-indicator indicator-success';
                            icon.className = 'fas fa-check-circle';
                            msg.textContent = data.message || 'Account created. You can now log in.';
                            form.reset();
                            setTimeout(function () {
                                window.location.href = base + (base.slice(-1) === '/' ? '' : '/') + 'index.php';
                            }, 2000);
                        } else {
                            indicator.className = 'login-indicator indicator-error';
                            icon.className = 'fas fa-exclamation-circle';
                            msg.textContent = data.message || 'Registration failed.';
                        }
                    })
                    .catch(function (err) {
                        console.error(err);
                        btn.disabled = false;
                        btn.textContent = 'Create Account';
                        indicator.style.display = 'flex';
                        indicator.className = 'login-indicator indicator-error';
                        icon.className = 'fas fa-wifi';
                        msg.textContent = 'Connection error. Please try again.';
                    });
            });
        })();
    </script>
</body>

</html>