<?php
require '../config/conn.php';
require '../config/session.php';
require '../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

// Set content type to JSON
header('Content-Type: application/json');


// Check if it's a POST request and has the required fields
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Check if register field exists OR if we have the form fields
    if (isset($_POST['register']) || (isset($_POST['full_name']) && isset($_POST['email']))) {
        
        // Retrieve and sanitize form data
        $full_name = trim($_POST['full_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $gender = $_POST['gender'] ?? '';
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        $newsletter_opt_in = isset($_POST['newsletter_opt_in']) ? 1 : 0;
        
        // Store form data in session in case of errors
        $_SESSION['form_data'] = [
            'full_name' => $full_name,
            'email' => $email,
            'phone' => $phone,
            'gender' => $gender,
            'newsletter_opt_in' => $newsletter_opt_in
        ];
        
        // Validate inputs
        $errors = [];
        
        // Name validation
        if (empty($full_name)) {
            $errors['full_name'] = "Full name is required";
        } elseif (!preg_match("/^[a-zA-Z ]*$/", $full_name)) {
            $errors['full_name'] = "Only letters and spaces allowed in name";
        }
        
        // Email validation
        if (empty($email)) {
            $errors['email'] = "Email is required";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = "Invalid email format";
        } else {
            // Check if email already exists
            $stmt = $conn->prepare("SELECT id FROM students WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            
            if ($stmt->num_rows > 0) {
                $errors['email'] = "Email already registered";
            }
            $stmt->close();
        }
        
        // Phone validation
        if (empty($phone)) {
            $errors['phone'] = "Phone number is required";
        } elseif (!preg_match("/^[0-9]{10,15}$/", $phone)) {
            $errors['phone'] = "Invalid phone number format (10-15 digits)";
        }
        
        // Password validation
        if (empty($password)) {
            $errors['password'] = "Password is required";
        } elseif (strlen($password) < 8) {
            $errors['password'] = "Password must be at least 8 characters";
        } elseif (!preg_match("/[A-Z]/", $password)) {
            $errors['password'] = "Password must contain at least one uppercase letter";
        } elseif (!preg_match("/[a-z]/", $password)) {
            $errors['password'] = "Password must contain at least one lowercase letter";
        } elseif (!preg_match("/[0-9]/", $password)) {
            $errors['password'] = "Password must contain at least one number";
        } elseif (!preg_match("/[^a-zA-Z0-9]/", $password)) {
            $errors['password'] = "Password must contain at least one special character";
        } elseif ($password !== $confirm_password) {
            $errors['confirm_password'] = "Passwords do not match";
        }
        
        // Gender validation
        if (empty($gender)) {
            $errors['gender'] = "Gender is required";
        }
        
        // Terms acceptance validation
        if (!isset($_POST['accept_terms'])) {
            $errors['terms'] = "You must accept the terms and conditions";
        }
        
        // If there are errors, return them as JSON
        if (!empty($errors)) {
            echo json_encode([
                'success' => false,
                'errors' => $errors,
                'message' => 'Please fix the errors below.',
                'debug' => 'Validation errors found'
            ]);
            exit();
        }
        
        // If no errors, proceed with registration
        // Generate unique student ID starting with Athenian
        $student_id = 'ATH' . strtoupper(substr(md5(uniqid()), 0, 8));
        
        // Generate registration number
        $student_reg_number = 'REG' . date('Y') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        
        // Generate verification token
        $verification_code = bin2hex(random_bytes(32));
        $verification_code_expiry = date('Y-m-d H:i:s', strtotime('+30 minutes'));
        
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        // Insert into database
        $stmt = $conn->prepare("INSERT INTO students (student_id, reg_number, full_name, email, phone, gender, password, verification_code, verification_code_expiry, newsletter_opt_in) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssssssi", $student_id, $student_reg_number, $full_name, $email, $phone, $gender, $hashed_password, $verification_code, $verification_code_expiry, $newsletter_opt_in);
        
        if ($stmt->execute()) {
            // Send verification email
            $mail = new PHPMailer(true);
            
            try {
                // Server settings
                 $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'holuwaseunisrael@gmail.com';
        $mail->Password   = 'ceae tepn tfyx oxjn';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;
                
                // Recipients
                $mail->setFrom('noreply@Athenian.com', 'Athenian');
                $mail->addAddress($email, $full_name);
                
                // Verification link
                $verification_link = "https://localhost/school-project/verify.php?code=$verification_code&email=" . urlencode($email);
                
                // Content
                $mail->isHTML(true);
                $mail->Subject = 'Welcome to Athenian - Verify Your Account';
                
                // HTML email body (your existing email template)
                $mail->Body = "
                <div style='max-width: 600px; margin: 0 auto; border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden; font-family: Arial, sans-serif;'>
                    <!-- Your email template here -->
                </div>
                ";
                
                $mail->AltBody = "Welcome to Athenian University, $full_name!\n\n" . "Your verification link: $verification_link";
                
                $mail->send();
                
                // Clear form data from session
                unset($_SESSION['form_data']);
                
                // Return success response
                echo json_encode([
                    'success' => true,
                    'message' => "Registration successful! We've sent a verification email to $email. Please check your inbox (and spam folder)."
                ]);
                exit();
                
            } catch (Exception $e) {
                // Email sending failed
                echo json_encode([
                    'success' => false,
                    'message' => "Registration completed but we couldn't send a verification email. Please contact support.",
                    'debug' => 'Email error: ' . $e->getMessage()
                ]);
                exit();
            }
        } else {
            echo json_encode([
                'success' => false,
                'message' => "Registration failed. Please try again.",
                'debug' => 'Database error'
            ]);
            exit();
        }
        
        $stmt->close();
    } else {
        // Missing required fields
        echo json_encode([
            'success' => false,
            'message' => 'Invalid request - missing form data.',
            'debug' => 'POST data: ' . print_r($_POST, true)
        ]);
        exit();
    }
} else {
    // Not a POST request
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method.',
        'debug' => 'Request method: ' . $_SERVER['REQUEST_METHOD']
    ]);
    exit();
}
?>