<?php
require_once 'auth_helper.php';

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = $_POST['student_id'] ?? '';
    $name = $_POST['name'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? 'Voter';
    
    // Simple validation
    if (!preg_match('/^\d{2}-\d{4}$/', $student_id)) {
        $error = 'Invalid Student ID format. Use XX-XXXX.';
    } else {
        try {
            // 1. Create user in Supabase
            $supabaseUser = SupabaseAuth::createUser($email, $password);
            $supabase_uid = null;
            if ($supabaseUser['error']) {
                if (str_contains(strtolower($supabaseUser['error']), 'already registered')) {
                    $sbUser = SupabaseAuth::getUserByEmail($email);
                    $supabase_uid = $sbUser['id'] ?? null;
                } else {
                    throw new Exception("Supabase Error: " . $supabaseUser['error']);
                }
            } else {
                $supabase_uid = $supabaseUser['data']['id'] ?? null;
            }

            $id = uuid();
            $stmt = db()->prepare("INSERT INTO users (id, supabase_uid, student_id, name, email, role) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$id, $supabase_uid, $student_id, $name, $email, $role]);
            
            $_SESSION['user_id'] = $id;
            $_SESSION['user_role'] = $role;
            audit_log('User registered', 'users', $id);
            header('Location: index.php');
            exit;
        } catch (PDOException $e) {
            if ($e->getCode() == 23000) {
                $error = 'Student ID or Email already exists.';
            } else {
                $error = 'An error occurred: ' . $e->getMessage();
            }
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration - Iloilo National High School</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@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/landing.css?v=<?= time() ?>">
    <style>
        .signup-page-container {
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2;
            position: relative;
            padding: 2rem 0;
        }
    </style>
</head>
<body class="landing-page" style="background-image: url('assets/images/background.jpg?v=<?= filemtime('assets/images/background.jpg') ?>');">
    <div class="signup-page-container">
        <div class="login-modal" style="display: block; position: static; animation: none; max-width: 500px;">
            <div class="modal-header">
                <div class="modal-header-content">
                    <div class="header-icon">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="8.5" cy="7" r="4"></circle><polyline points="17 11 19 13 23 9"></polyline></svg>
                    </div>
                    <h2>Voter Registration</h2>
                </div>
            </div>
            <div class="modal-body">
                <?php if ($error): ?>
                    <div style="background: #fee2e2; color: #b91c1c; padding: 0.75rem; border-radius: 10px; margin-bottom: 1.5rem; font-size: 0.85rem; border: 1px solid #fecaca; text-align: center;">
                        <?= htmlspecialchars($error) ?>
                    </div>
                <?php endif; ?>
                <form method="POST">
                    <div class="form-group">
                        <label>Full Name</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                            </i>
                            <input type="text" name="name" placeholder="Juan Dela Cruz" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>UID</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"></rect><line x1="7" y1="8" x2="17" y2="8"></line><line x1="7" y1="12" x2="17" y2="12"></line><line x1="7" y1="16" x2="12" y2="16"></line></svg>
                            </i>
                            <input type="text" name="student_id" placeholder="00-0000" required pattern="\d{2}-\d{4}">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Email Account</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline></svg>
                            </i>
                            <input type="email" name="email" placeholder="firstname.lastname@iloilonhs.edu.ph" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Password</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                            </i>
                            <input type="password" id="passwordInput" name="password" placeholder="Create a password" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>User Type</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                            </i>
                            <select name="role">
                                <option value="Voter">Voter</option>
                                <option value="Officer">Officer</option>
                                <option value="Adviser">Adviser</option>
                                <option value="Admin">Admin</option>
                            </select>
                        </div>
                    </div>

                    <button type="submit" class="modal-btn-login">
                        REGISTER
                    </button>
                </form>
                <div class="text-center mt-3">
                    <small style="color: var(--landing-text-muted); font-size: 0.8rem;">Already have an account? <a href="login.php" style="color: var(--landing-primary); font-weight: 600; text-decoration: none;">Login here</a></small>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
