<?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
    $business_name = trim($_POST['business_name']);
    $email = trim($_POST['email']);
    $contact_person = trim($_POST['contact_person']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Store form data in session in case of errors
    $_SESSION['form_data'] = [
        'business_name' => $business_name,
        'email' => $email,
        'contact_person' => $contact_person
    ];
    
    // Validate inputs
    $errors = [];
    
    // Business name validation
    if (empty($business_name)) {
        $errors['business_name'] = "Business name is required";
    } elseif (strlen($business_name) < 3) {
        $errors['business_name'] = "Business name must be at least 3 characters";
    }
    
    // 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 vendors WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();
        
        if ($stmt->num_rows > 0) {
            $errors['email'] = "Email already registered";
        }
        $stmt->close();
    }
    
    // Contact person validation
    if (empty($contact_person)) {
        $errors['contact_person'] = "Contact person name is required";
    } elseif (!preg_match("/^[a-zA-Z ]*$/", $contact_person)) {
        $errors['contact_person'] = "Only letters and spaces allowed in name";
    }
    
    // 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";
    }
    
    // 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: vendor-registration.php");
        exit();
    }
    
    // If no errors, proceed with registration
    // Generate unique vendor ID
    $vendor_id = 'VEND' . 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);
    
    // Insert into database
    $stmt = $conn->prepare("INSERT INTO vendors (vendor_id, business_name, email, contact_person, password, verification_code, verification_code_expiry) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssss", $vendor_id, $business_name, $email, $contact_person, $hashed_password, $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@vendorportal.com', 'Vendor Portal');
            $mail->addAddress($email, $contact_person);
            
            // Verification link
            $verification_link = "https://localhost/school-project/vendors/verify.php?code=$verification_code&email=" . urlencode($email);
            
            // Content
            $mail->isHTML(true);
            $mail->Subject = 'Welcome to Vendor Portal - Verify Your Account';
            
            $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: white; margin: 0; font-size: 24px;'>Vendor Portal</h1>
                        <p style='color: rgba(255,255,255,0.8); margin: 5px 0 0; font-size: 16px;'>
                            Business Partner Registration
                        </p>
                    </div>
                    
                    <div style='padding: 25px;'>
                        <h2 style='color: #fbbb01; margin-top: 0;'>Welcome to Vendor Portal, $contact_person!</h2>
                        
                        <p style='font-size: 16px;'>Thank you for registering with Vendor Portal. To complete your registration, please verify your email address.</p>
                        
                        <div style='background-color: #fef8e6; border-left: 4px solid #fbbb01; padding: 15px; margin: 20px 0;'>
                            <h3 style='color: #fbbb01; margin-top: 0;'>Your Vendor Account</h3>
                            <p style='font-size: 16px;'><strong>Business Name:</strong> $business_name</p>
                            <p style='font-size: 16px;'><strong>Vendor ID:</strong> $vendor_id</p>
                            <p>Your account will be reviewed by our team before approval.</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: white; 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>
                    </div>
                    
                    <div style='background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666;'>
                        <p>© " . date('Y') . " Vendor Portal. All rights reserved.</p>
                    </div>
                </div>
            ";
            
            $mail->AltBody = "Welcome to Vendor Portal, $contact_person!\n\n"
                . "Thank you for registering with Vendor Portal. To complete your registration, please verify your email address.\n\n"
                . "Your Vendor Account:\n"
                . "Business Name: $business_name\n"
                . "Vendor ID: $vendor_id\n\n"
                . "Your account will be reviewed by our team before approval.\n\n"
                . "Please verify your email by visiting this link:\n$verification_link\n\n"
                . "This link expires in 30 minutes.\n\n"
                . "If you didn't request this, please ignore this email.\n\n"
                . "Best regards,\n"
                . "Vendor Portal Team";
            
            $mail->send();
            
            // Clear form data from session
            unset($_SESSION['form_data']);
            
            // Set success message
            $_SESSION['success_message'] = "Registration successful! We've sent a verification email to $email. Please check your inbox (and spam folder). Your account will be reviewed by our team before approval.";
            
            // Redirect to registration page with success message
            header("Location: vendor-registration.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: vendor-registration.php");
            exit();
        }
    } else {
        $errors[] = "Registration failed. Please try again.";
        $_SESSION['error_messages'] = $errors;
        header("Location: vendor-registration.php");
        exit();
    }
    
    $stmt->close();
}

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