<?php
session_start();
require_once 'config/database.php';
require_once 'includes/functions.php';
require_once 'includes/email_templates.php';

try {
    // Get database connection
    $database = new Database();
    $db = $database->getConnection();
    
    // Start transaction
    $db->beginTransaction();

    // Validate required fields
    $requiredFields = [
        'firstName', 'lastName', 'email', 'phone', 'dob', 'gender', 
        'country', 'address', 'accountType', 'currency', 'username', 
        'password', 'pin', 'kinName', 'kinEmail', 'kinPhone', 'kinAddress',
        'employmentStatus', 'incomeSource'
    ];

    foreach ($requiredFields as $field) {
        if (!isset($_POST[$field]) || empty($_POST[$field])) {
            $_SESSION['error'] = ucfirst(str_replace('_', ' ', $field)) . ' is required';
            header('Location: register.php');
            exit;
        }
    }

    // Validate email format
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $_SESSION['error'] = 'Invalid email format';
        header('Location: register.php');
        exit;
    }

    // Check if email exists
    $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$_POST['email']]);
    if ($stmt->fetch()) {
        $_SESSION['error'] = 'Email already registered';
        header('Location: register.php');
        exit;
    }

    // Check if username exists
    $stmt = $db->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$_POST['username']]);
    if ($stmt->fetch()) {
        $_SESSION['error'] = 'Username already taken';
        header('Location: register.php');
        exit;
    }

    // Generate account number
    $accountNumber = date('Y') . mt_rand(100000, 999999);

    // Handle profile picture upload
    $profilePicture = '';
    $targetPath = '';
    if (isset($_FILES['profilePicture']) && $_FILES['profilePicture']['error'] === 0) {
        $uploadDir = 'uploads/profiles/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $allowedTypes = ['image/jpeg', 'image/png'];
        $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($fileInfo, $_FILES['profilePicture']['tmp_name']);
        finfo_close($fileInfo);

        if (!in_array($mimeType, $allowedTypes)) {
            $_SESSION['error'] = 'Invalid file type. Only JPG and PNG files are allowed.';
            header('Location: register.php');
            exit;
        }

        if ($_FILES['profilePicture']['size'] > 5 * 1024 * 1024) {
            $_SESSION['error'] = 'File size too large. Maximum size is 5MB.';
            header('Location: register.php');
            exit;
        }

        $extension = strtolower(pathinfo($_FILES['profilePicture']['name'], PATHINFO_EXTENSION));
        $fileName = uniqid() . '_' . time() . '.' . $extension;
        $targetPath = $uploadDir . $fileName;

        if (!move_uploaded_file($_FILES['profilePicture']['tmp_name'], $targetPath)) {
            $_SESSION['error'] = 'Error uploading profile picture.';
            header('Location: register.php');
            exit;
        }

        $profilePicture = $fileName;
    }

    // Hash password and PIN
    $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $hashedPin = password_hash($_POST['pin'], PASSWORD_DEFAULT);

    // Generate email verification code
    $verificationCode = bin2hex(random_bytes(16));
    $verificationExpiry = date('Y-m-d H:i:s', strtotime('+24 hours'));

    // Insert user data
    $stmt = $db->prepare("
        INSERT INTO users (
            first_name, last_name, email, phone, date_of_birth, 
            gender, country, address, account_type, currency, 
            username, password, pin, account_number, profile_picture,
            employment_status, income_source, status, verification_code, verification_expiry, created_at
        ) VALUES (
            :firstName, :lastName, :email, :phone, :dob,
            :gender, :country, :address, :accountType, :currency,
            :username, :password, :pin, :accountNumber, :profilePicture,
            :employmentStatus, :incomeSource, 'pending', :verificationCode, :verificationExpiry, NOW()
        )
    ");

    $stmt->execute([
        ':firstName' => $_POST['firstName'],
        ':lastName' => $_POST['lastName'],
        ':email' => $_POST['email'],
        ':phone' => $_POST['phone'],
        ':dob' => $_POST['dob'],
        ':gender' => $_POST['gender'],
        ':country' => $_POST['country'],
        ':address' => $_POST['address'],
        ':accountType' => $_POST['accountType'],
        ':currency' => $_POST['currency'],
        ':username' => $_POST['username'],
        ':password' => $hashedPassword,
        ':pin' => $hashedPin,
        ':accountNumber' => $accountNumber,
        ':profilePicture' => $profilePicture,
        ':employmentStatus' => $_POST['employmentStatus'],
        ':incomeSource' => $_POST['incomeSource'],
        ':verificationCode' => $verificationCode,
        ':verificationExpiry' => $verificationExpiry
    ]);

    $userId = $db->lastInsertId();

    // Insert next of kin data
    $stmt = $db->prepare("
        INSERT INTO next_of_kin (
            user_id, full_name, email, phone, address, created_at
        ) VALUES (
            :userId, :fullName, :email, :phone, :address, NOW()
        )
    ");

    $stmt->execute([
        ':userId' => $userId,
        ':fullName' => $_POST['kinName'],
        ':email' => $_POST['kinEmail'],
        ':phone' => $_POST['kinPhone'],
        ':address' => $_POST['kinAddress']
    ]);

    // Create initial balance record
    $stmt = $db->prepare("
        INSERT INTO account_balances (
            user_id, account_number, currency, balance, last_updated
        ) VALUES (
            :userId, :accountNumber, :currency, 0, NOW()
        )
    ");

    $stmt->execute([
        ':userId' => $userId,
        ':accountNumber' => $accountNumber,
        ':currency' => $_POST['currency']
    ]);

    // Create admin notification for new user registration
    if (function_exists('notifyAdminNewUser')) {
        try {
            notifyAdminNewUser(
                $db, 
                $userId, 
                $_POST['firstName'] . ' ' . $_POST['lastName'], 
                $_POST['email']
            );
        } catch (Exception $e) {
            // Log but don't stop the process
            error_log("Failed to create admin notification: " . $e->getMessage());
        }
    }

    // Commit transaction
    $db->commit();

    // Send registration confirmation email
    $userName = $_POST['firstName'] . ' ' . $_POST['lastName'];
    
    try {
        // Log email attempt
        error_log("Attempting to send registration email to: " . $_POST['email']);
        
        // Send the email
        $emailSent = sendRegistrationEmail($_POST['email'], $userName, $accountNumber, $verificationCode);
        
        // Log the result
        if ($emailSent) {
            error_log("Registration email sent successfully to: " . $_POST['email']);
            $_SESSION['email_sent'] = true;
        } else {
            error_log("Failed to send registration email to: " . $_POST['email']);
            $_SESSION['email_sent'] = false;
        }
    } catch (Exception $e) {
        // Log the exception but continue with the registration process
        error_log("Exception when sending registration email: " . $e->getMessage());
        $_SESSION['email_sent'] = false;
    }

    // Store success message and account details in session
    $_SESSION['success'] = true;
    $_SESSION['account_number'] = $accountNumber;
    $_SESSION['registered_email'] = $_POST['email'];
    
    // Add debug information if email sending failed
    if (!isset($_SESSION['email_sent']) || $_SESSION['email_sent'] === false) {
        $_SESSION['email_debug'] = [
            'attempted' => true,
            'time' => date('Y-m-d H:i:s'),
            'to' => $_POST['email']
        ];
    }

    // Redirect to success page
    header('Location: registration_success.php');
    exit;

} catch (Exception $e) {
    // Rollback transaction on error
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }

    // Delete uploaded file if exists
    if (!empty($targetPath) && file_exists($targetPath)) {
        unlink($targetPath);
    }

    // Log detailed error
    error_log("Registration error: " . $e->getMessage());
    error_log("Error trace: " . $e->getTraceAsString());

    // Store error message and redirect
    $_SESSION['error'] = "Registration failed: " . $e->getMessage();
    header('Location: register.php');
    exit;
}
?>
