<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/User.php';
require_once __DIR__ . '/../config/helpers/notification.php';

if (isLoggedIn()) {
    redirect('dashboard.php');
}

$user = new User();
$error = null;
$success = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $firstName = trim($_POST['first_name'] ?? '');
    $lastName = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['password_confirmation'] ?? '';
    $region = trim($_POST['region'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    if ($password !== $confirmPassword) {
        $error = 'Passwords do not match.';
    } elseif ($phone === '') {
        $error = 'Phone number is required.';
    } elseif (!preg_match('/^[0-9+\-\s()]{7,20}$/', $phone)) {
        $error = 'Please enter a valid phone number.';
    } else {
        // Validate region input (allowed regions are usa, europe, africa)
        $allowedRegions = ['usa','europe','africa'];
        if (!in_array($region, $allowedRegions, true)) {
            $region = DEFAULT_REGION;
        }

        $data = [
            'first_name' => $firstName,
            'last_name'  => $lastName,
            // Use the email address as the username
            'username'   => $email,
            'email'      => $email,
            'password'   => $password,
            'region'     => $region,
            'phone'      => $phone,
        ];

        try {
            $userId = $user->register($data);

            $db = Database::getInstance();
            $db->update('users', [
                'status' => 'active',
                'email_verified' => 1,
                'email_verification_token' => null,
            ], 'id = ?', [$userId]);

            // Send welcome email and SMS (if phone is available and SMS is enabled)
            sendUserWelcomeNotification($userId);

            setFlashMessage('success', 'Registration successful. You can now log in.');
            redirect('login.php');
        } 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>Register - SmartThink</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            min-height: 100vh;
            font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background-color: #020617;
            color: #e5e7eb;
        }

        .register-page {
            position: relative;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem 1rem;
            background: url('../assets/images/csimg.jpeg') center center / cover no-repeat fixed;
        }

        .register-page::before {
            content: '';
            position: absolute;
            inset: 0;
            background: linear-gradient(to bottom, rgba(15, 23, 42, 0.88), rgba(15, 23, 42, 0.94));
        }

        .register-wrapper {
            position: relative;
            width: 100%;
            max-width: 480px;
            z-index: 1;
        }

        .register-top-title {
            text-align: center;
            font-size: 0.85rem;
            letter-spacing: 0.18em;
            text-transform: uppercase;
            color: rgba(249, 250, 251, 0.85);
            margin-bottom: 0.75rem;
        }

        .register-card {
            background: rgba(15, 23, 42, 0.92);
            border-radius: 0.75rem;
            padding: 2rem 2.25rem;
            box-shadow: 0 24px 72px rgba(15, 23, 42, 0.9);
            backdrop-filter: blur(8px);
        }

        .register-heading {
            font-size: 1.4rem;
            font-weight: 600;
            text-align: center;
            margin-bottom: 0.25rem;
        }

        .register-subtitle {
            font-size: 0.9rem;
            text-align: center;
            color: #9ca3af;
            margin-bottom: 1.5rem;
        }

        .form-label {
            font-size: 0.85rem;
            color: #e5e7eb;
        }

        .form-control,
        .form-select {
            background-color: rgba(15, 23, 42, 0.96);
            border-color: #1f2937;
            color: #e5e7eb;
        }

        .form-control::placeholder,
        .form-select::placeholder {
            color: #6b7280;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: #0ea5e9;
            box-shadow: 0 0 0 1px rgba(14, 165, 233, 0.7);
            background-color: rgba(15, 23, 42, 0.98);
            color: #e5e7eb;
        }

        .form-text {
            color: #6b7280;
            font-size: 0.75rem;
        }

        .register-submit-btn {
            background: linear-gradient(to right, #0ea5e9, #22c55e);
            border: none;
            border-radius: 999px;
            font-weight: 600;
        }

        .register-submit-btn:hover {
            background: linear-gradient(to right, #0284c7, #16a34a);
        }

        .register-accent-bar {
            height: 4px;
            width: 100%;
            border-radius: 999px;
            background: linear-gradient(to right, #0ea5e9, #22c55e);
        }

        .register-footer-text {
            margin-top: 1.25rem;
            text-align: center;
            font-size: 0.75rem;
            color: #9ca3af;
        }

        .text-muted-link {
            color: #9ca3af;
            text-decoration: none;
        }

        .text-muted-link:hover {
            color: #e5e7eb;
        }

        .alert {
            border-radius: 0.5rem;
            font-size: 0.85rem;
        }

        @media (max-width: 576px) {
            .register-card {
                padding: 1.5rem 1.25rem;
            }

            .register-heading {
                font-size: 1.25rem;
            }
        }
    </style>
</head>
<body>
    <div class="register-page">
        <div class="register-wrapper">
            <div class="register-top-title">
                COURSE REGISTRATION FORM
            </div>
            <div class="register-card">
                <h2 class="register-heading">Training Course</h2>
                <p class="register-subtitle">Create your SmartThink learning account to enrol in training courses and track your progress.</p>

                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger py-2 mb-3" role="alert">
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>

                <form method="post" novalidate>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="first_name" class="form-label">First Name</label>
                            <input type="text" class="form-control" id="first_name" name="first_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="last_name" class="form-label">Last Name</label>
                            <input type="text" class="form-control" id="last_name" name="last_name" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email Address</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>

                    <div class="mb-3">
                        <label for="phone" class="form-label">Phone Number</label>
                        <input type="tel" class="form-control" id="phone" name="phone" required>
                        <div class="form-text">Include your country code if possible, e.g. +233 24 123 4567.</div>
                    </div>

                    <div class="mb-3">
                        <label for="region" class="form-label">Continent / Region</label>
                        <select name="region" id="region" class="form-select" required>
                            <option value="usa">USA</option>
                            <option value="europe">Europe</option>
                            <option value="africa">Africa</option>
                        </select>
                        <div class="form-text">Select the continent/region for content and course visibility.</div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="password_confirmation" class="form-label">Confirm Password</label>
                            <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" required>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary w-100 mb-3 register-submit-btn">
                        <i class="fas fa-user-plus me-2"></i>Create Account
                    </button>

                    <div class="register-accent-bar mb-2"></div>

                    <div class="text-center small text-muted mt-3">
                        Already have an account?
                        <a href="login.php" class="text-muted-link">Login here</a>
                    </div>
                </form>
            </div>
            <div class="register-footer-text">
                &copy; <?php echo date('Y'); ?> SmartThink. All rights reserved.
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
