<?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;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register'])) {
    // 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'];
    
    // Store form data in session in case of errors
    $_SESSION['form_data'] = [
        'full_name' => $full_name,
        'email' => $email,
        'phone' => $phone,
        'gender' => $gender
    ];
    
    // 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 admins 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, store them in session and redirect back
    if (!empty($errors)) {
        $_SESSION['validation_errors'] = $errors;
        header("Location: register.php");
        exit();
    }
    
    // If no errors, proceed with registration
    // Generate unique admin ID
    $admin_id = 'ADM' . strtoupper(substr(md5(uniqid()), 0, 8));
    
    // 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);
    
    // Default role for new admins (can be changed by super admin later)
    $role = 'admin';
    
    // Insert into database
    $stmt = $conn->prepare("INSERT INTO admins (admin_id, full_name, email, phone, gender, password, role, verification_code, verification_code_expiry) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssssss", $admin_id, $full_name, $email, $phone, $gender, $hashed_password, $role, $verification_code, $verification_code_expiry);
    
    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@admin-portal.com', 'Admin Portal');
            $mail->addAddress($email, $full_name);
            
            // Verification link
             $verification_link = "https://localhost/school-project/admin/verify.php?code=$verification_code&email=" . urlencode($email);
            
            
            // Content
            $mail->isHTML(true);
            $mail->Subject = 'Admin Account Verification';
            
            // HTML email body with original color scheme
            $mail->Body = "
            <div style='max-width: 600px; margin: 0 auto; border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden; font-family: Arial, sans-serif;'>
                <div style='background-color: #FBBB01; padding: 25px; text-align: center;'>
                    <h1 style='color: black; margin: 0; font-size: 24px;'>Admin Portal</h1>
                    <p style='color: rgba(0,0,0,0.8); margin: 5px 0 0; font-size: 16px;'>
                        Management System
                    </p>
                </div>
                
                <div style='padding: 25px;'>
                    <h2 style='color: #FBBB01; margin-top: 0;'>Welcome, $full_name!</h2>
                    
                    <p style='font-size: 16px;'>Your admin account has been created. To complete the registration process, please verify your email address.</p>
                    
                    <div style='background-color: #fff9e6; border-left: 4px solid #FBBB01; padding: 15px; margin: 20px 0;'>
                        <h3 style='color: #FBBB01; margin-top: 0;'>🔒 Admin Account Details</h3>
                        <p style='font-size: 16px;'><strong>Admin ID:</strong> <span style='font-weight: bold; color: #FBBB01;'>$admin_id</span></p>
                        <p style='font-size: 16px;'><strong>Role:</strong> <span style='font-weight: bold;'>" . ucfirst($role) . "</span></p>
                    </div>
                    
                    <div style='background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin: 20px 0; text-align: center;'>
                        <a href='$verification_link' style='display: inline-block; padding: 12px 25px; background-color: #FBBB01; color: black; text-decoration: none; border-radius: 5px; font-weight: bold; margin-bottom: 15px;'>
                            Verify Your Email
                        </a>
                        <p style='margin-bottom: 5px; font-size: 14px;'>Or copy this link:</p>
                        <div style='background-color: #f1f1f1; padding: 10px; border-radius: 3px; word-break: break-all; font-family: monospace; font-size: 14px; color: #333;'>
                            $verification_link
                        </div>
                        <p style='font-size: 13px; color: #666; margin-top: 5px;'>⏳ Link expires in 30 minutes</p>
                    </div>
                    
                    <p style='font-size: 14px; color: #666;'>After verification, a super admin will need to activate your account before you can access the system.</p>
                </div>
                
                <div style='background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666;'>
                    <p>© " . date('Y') . " Admin Portal. All rights reserved.</p>
                </div>
            </div>
            ";
            
            $mail->AltBody = "Welcome to the Admin Portal, $full_name!\n\n"
                . "Your admin account has been created with the following details:\n"
                . "Admin ID: $admin_id\n"
                . "Role: $role\n\n"
                . "Please verify your email by visiting this link:\n$verification_link\n\n"
                . "This link expires in 30 minutes.\n\n"
                . "After verification, a super admin will need to activate your account before you can access the system.\n\n"
                . "If you didn't request this, please ignore this email.\n\n"
                . "Best regards,\n"
                . "Admin Portal Team";
            
            $mail->send();
            
            // Clear form data from session
            unset($_SESSION['form_data']);
            
            // Set success message
            $_SESSION['success_message'] = "Admin registration submitted! We've sent a verification email to $email. Please check your inbox (and spam folder). A super admin will need to activate your account after verification.";
            
            // Redirect to registration page with success message
            header("Location: register.php");
            exit();
            
        } catch (Exception $e) {
            // Email sending failed
            $errors[] = "Registration completed but we couldn't send a verification email. Please contact support.";
            $_SESSION['error_messages'] = $errors;
            header("Location: register.php");
            exit();
        }
    } else {
        $errors[] = "Registration failed. Please try again.";
        $_SESSION['error_messages'] = $errors;
        header("Location: register.php");
        exit();
    }
    
    $stmt->close();
}

// Redirect if accessed directly
header("Location: register.php");
exit();
?>