<?php
require_once 'includes/auth_check.php';
$page = 'users'; // To keep 'Manage Users' active in the sidebar
require_once '../config/database.php';
require_once '../includes/email_templates.php'; // Include email templates

// For debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Define necessary functions directly in this file
function checkEmailExists($db, $email) {
    $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    return $stmt->fetch() !== false;
}

function checkUsernameExists($db, $username) {
    $stmt = $db->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$username]);
    return $stmt->fetch() !== false;
}

function generateAccountNumber($db) {
    do {
        $accountNumber = date('Y') . mt_rand(100000, 999999);
        $stmt = $db->prepare("SELECT id FROM users WHERE account_number = ?");
        $stmt->execute([$accountNumber]);
    } while ($stmt->fetch());
    
    return $accountNumber;
}

function generateSecurityCodes() {
    return [
        'cot' => strtoupper(bin2hex(random_bytes(3))),
        'imf' => strtoupper(bin2hex(random_bytes(3))),
        'tax' => strtoupper(bin2hex(random_bytes(3)))
    ];
}

$database = new Database();
$db = $database->getConnection();

// --- Handle Form Submission (POST Request) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Check
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error_message'] = "Invalid security token. Please try again.";
    } else {
        // Sanitize and retrieve form data
        $firstName = trim($_POST['firstName']);
        $lastName = trim($_POST['lastName']);
        $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
        $phone = trim($_POST['phone']);
        $dob = $_POST['dob'];
        $gender = $_POST['gender'];
        $country = $_POST['country'];
        $address = trim($_POST['address']);
        
        // Next of kin details
        $kinName = trim($_POST['kinName']);
        $kinRelationship = $_POST['kinRelationship'];
        $kinEmail = filter_var(trim($_POST['kinEmail']), FILTER_SANITIZE_EMAIL);
        $kinPhone = trim($_POST['kinPhone']);
        $kinAddress = trim($_POST['kinAddress']);
        
        // Account details
        $accountType = $_POST['accountType'];
        $currency = $_POST['currency'];
        $employmentStatus = $_POST['employmentStatus'];
        $incomeSource = $_POST['incomeSource'];
        $initial_balance = filter_input(INPUT_POST, 'initial_balance', FILTER_VALIDATE_FLOAT);
        $status = $_POST['status'];
        
        // Security details
        $username = trim($_POST['username']);
        $password = $_POST['password'];
        $confirmPassword = $_POST['confirmPassword'];
        $pin = $_POST['pin'] ?? '0000'; // Default to 0000 if not provided

        // Validation
        if (empty($firstName) || empty($lastName) || empty($email) || empty($username) || empty($password)) {
            $_SESSION['error_message'] = "Please fill in all required fields.";
        } elseif ($password !== $confirmPassword) {
            $_SESSION['error_message'] = "Passwords do not match.";
        } elseif (strlen($password) < 8) {
            $_SESSION['error_message'] = "Password must be at least 8 characters long.";
        } elseif (checkEmailExists($db, $email)) {
            $_SESSION['error_message'] = "An account with this email address already exists.";
        } elseif (checkUsernameExists($db, $username)) {
            $_SESSION['error_message'] = "This username is already taken.";
        } else {
            // 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_message'] = 'Invalid file type. Only JPG and PNG files are allowed.';
                    header("Location: add_user.php");
                    exit;
                }

                if ($_FILES['profilePicture']['size'] > 5 * 1024 * 1024) {
                    $_SESSION['error_message'] = 'File size too large. Maximum size is 5MB.';
                    header("Location: add_user.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_message'] = 'Error uploading profile picture.';
                    header("Location: add_user.php");
                    exit;
                }

                $profilePicture = $fileName;
            }

            // All validation passed, proceed with creating the user
            try {
                $db->beginTransaction();

                // 1. Prepare user data
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $hashed_pin = password_hash($pin, PASSWORD_DEFAULT);
                $account_number = generateAccountNumber($db);
                $security_codes = generateSecurityCodes();
                $verificationCode = bin2hex(random_bytes(16));
                $verificationExpiry = date('Y-m-d H:i:s', strtotime('+24 hours'));

                // 2. Create the user record
                $user_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, role, email_verified, 
                        verification_code, verification_expiry, created_at
                    ) VALUES (
                        :firstName, :lastName, :email, :phone, :dob, :gender, :country, :address, 
                        :accountType, :currency, :username, :password, :pin, :account_number, :profilePicture,
                        :employmentStatus, :incomeSource, :status, 'user', 1, 
                        :verificationCode, :verificationExpiry, NOW()
                    )
                ");
                $user_stmt->execute([
                    ':firstName' => $firstName,
                    ':lastName' => $lastName,
                    ':email' => $email,
                    ':phone' => $phone,
                    ':dob' => $dob,
                    ':gender' => $gender,
                    ':country' => $country,
                    ':address' => $address,
                    ':accountType' => $accountType,
                    ':currency' => $currency,
                    ':username' => $username,
                    ':password' => $hashed_password,
                    ':pin' => $hashed_pin,
                    ':account_number' => $account_number,
                    ':profilePicture' => $profilePicture,
                    ':employmentStatus' => $employmentStatus,
                    ':incomeSource' => $incomeSource,
                    ':status' => $status,
                    ':verificationCode' => $verificationCode,
                    ':verificationExpiry' => $verificationExpiry
                ]);

                $new_user_id = $db->lastInsertId();

                // 3. Create the initial account balance record
                $balance_stmt = $db->prepare("INSERT INTO account_balances (user_id, account_number, currency, balance, last_updated) VALUES (?, ?, ?, ?, NOW())");
                $balance_stmt->execute([$new_user_id, $account_number, $currency, $initial_balance ?? 0.00]);

                // 4. Create the security codes record
                $codes_stmt = $db->prepare("INSERT INTO security_codes (user_id, cot_code, imf_code, tax_code) VALUES (?, ?, ?, ?)");
                $codes_stmt->execute([$new_user_id, $security_codes['cot'], $security_codes['imf'], $security_codes['tax']]);
                
                // 5. Create next_of_kin record
                $kin_stmt = $db->prepare("INSERT INTO next_of_kin (user_id, full_name, relationship, email, phone, address, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
                $kin_stmt->execute([$new_user_id, $kinName, $kinRelationship, $kinEmail, $kinPhone, $kinAddress]);

                // If all queries were successful, commit the transaction
                $db->commit();
                
                // Send welcome email with PIN and security codes
                $fullName = $firstName . ' ' . $lastName;
                
                // Try to use the email_templates.php function if available
                $emailSent = false;
                if (function_exists('sendRegistrationEmail')) {
                    $emailSent = sendRegistrationEmail($email, $fullName, $account_number, $verificationCode);
                } else {
                    // Fallback to the local function
                    $emailSent = sendWelcomeEmail($email, $fullName, $username, $account_number, ucfirst($accountType), $security_codes);
                }
                
                $_SESSION['success_message'] = "User '" . htmlspecialchars($username) . "' was created successfully with Account Number: " . $account_number . 
                    ($emailSent ? " and a welcome email was sent." : " but the welcome email could not be sent.");
                
                header("Location: manage_users.php");
                exit;

            } catch (Exception $e) {
                // If any error occurs, roll back all database changes
                $db->rollBack();
                
                // Delete uploaded file if exists
                if (!empty($targetPath) && file_exists($targetPath)) {
                    unlink($targetPath);
                }
                
                error_log("Add User DB Error: " . $e->getMessage());
                $_SESSION['error_message'] = "Failed to create user due to a database error: " . $e->getMessage();
            }
        }
    }
    // Redirect back to the add user page if there was an error
    header("Location: add_user.php");
    exit;
}

// Generate a CSRF token for the form for GET requests
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

include 'includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Add New User</h1>

    <!-- Display Success/Error Messages -->
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">New User Details</h6>
            <a href="manage_users.php" class="btn btn-sm btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Users
            </a>
        </div>
        <div class="card-body">
            <form action="add_user.php" method="POST" id="addUserForm" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                
                <!-- Step Progress Indicator -->
                <div class="mb-4">
                    <ul class="nav nav-pills nav-justified step-progress" id="userFormTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="personal-tab" data-bs-toggle="pill" data-bs-target="#personal" type="button" role="tab" aria-selected="true">
                                <span class="step-number">1</span>
                                <span class="d-none d-md-inline ms-2">Personal Info</span>
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="profile-tab" data-bs-toggle="pill" data-bs-target="#profile" type="button" role="tab" aria-selected="false">
                                <span class="step-number">2</span>
                                <span class="d-none d-md-inline ms-2">Profile</span>
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="account-tab" data-bs-toggle="pill" data-bs-target="#account" type="button" role="tab" aria-selected="false">
                                <span class="step-number">3</span>
                                <span class="d-none d-md-inline ms-2">Account</span>
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="security-tab" data-bs-toggle="pill" data-bs-target="#security" type="button" role="tab" aria-selected="false">
                                <span class="step-number">4</span>
                                <span class="d-none d-md-inline ms-2">Security</span>
                            </button>
                        </li>
                    </ul>
                </div>
                
                <!-- Form Content -->
                <div class="tab-content" id="userFormContent">
                    <!-- Step 1: Personal Information -->
                    <div class="tab-pane fade show active" id="personal" role="tabpanel" aria-labelledby="personal-tab">
                        <h5 class="mb-4">Personal Information</h5>
                        <div class="row g-3">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">First Name</label>
                                <input type="text" class="form-control" name="firstName" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Last Name</label>
                                <input type="text" class="form-control" name="lastName" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email Address</label>
                                <input type="email" class="form-control" name="email" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Phone Number</label>
                                <input type="tel" class="form-control" name="phone" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Date of Birth</label>
                                <input type="date" class="form-control" name="dob" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Gender</label>
                                <select class="form-select" name="gender" required>
                                    <option value="">Select Gender</option>
                                    <option value="male">Male</option>
                                    <option value="female">Female</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Country</label>
                                <select class="form-select" name="country" required>
                                    <option value="">Select Country</option>
                                    <option value="US">United States</option>
                                    <option value="GB">United Kingdom</option>
                                    <option value="CA">Canada</option>
                                    <option value="AU">Australia</option>
                                    <option value="DE">Germany</option>
                                    <option value="FR">France</option>
                                    <!-- Add more countries as needed -->
                                </select>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" name="address" rows="3" required></textarea>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end mt-4">
                            <button type="button" class="btn btn-primary" onclick="nextTab('profile-tab')">
                                Continue <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 2: Profile & Documents -->
                    <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                        <h5 class="mb-4">Profile Setup</h5>
                        
                        <!-- Profile Picture Upload -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="d-flex align-items-center">
                                    <div class="profile-preview me-4">
                                        <img src="../assets/images/default-avatar.png" id="profilePreview" alt="Profile Preview" 
                                             style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 3px solid #e2e8f0;">
                                    </div>
                                    <div>
                                        <h6 class="mb-2">Profile Picture</h6>
                                        <p class="text-muted mb-2">Upload a clear photo of the user</p>
                                        <input type="file" id="profilePicture" name="profilePicture" class="form-control" accept="image/*">
                                        <small class="text-muted">Max file size: 5MB (JPG or PNG)</small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Next of Kin Information -->
                        <h5 class="mb-4">Next of Kin Details</h5>
                        <div class="row g-3">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Full Name</label>
                                <input type="text" class="form-control" name="kinName" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Relationship</label>
                                <select class="form-select" name="kinRelationship" required>
                                    <option value="">Select Relationship</option>
                                    <option value="spouse">Spouse</option>
                                    <option value="parent">Parent</option>
                                    <option value="child">Child</option>
                                    <option value="sibling">Sibling</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email Address</label>
                                <input type="email" class="form-control" name="kinEmail" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Phone Number</label>
                                <input type="tel" class="form-control" name="kinPhone" required>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" name="kinAddress" rows="3" required></textarea>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-outline-secondary" onclick="nextTab('personal-tab')">
                                <i class="fas fa-arrow-left"></i> Back
                            </button>
                            <button type="button" class="btn btn-primary" onclick="nextTab('account-tab')">
                                Continue <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 3: Account Details -->
                    <div class="tab-pane fade" id="account" role="tabpanel" aria-labelledby="account-tab">
                        <h5 class="mb-4">Account Setup</h5>
                        <div class="row g-3">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Account Type</label>
                                <select class="form-select" name="accountType" required>
                                    <option value="">Select Account Type</option>
                                    <option value="savings">Savings Account</option>
                                    <option value="checking">Checking Account</option>
                                    <option value="business">Business Account</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Currency</label>
                                <select class="form-select" name="currency" required>
                                    <option value="">Select Currency</option>
                                    <option value="USD">US Dollar (USD)</option>
                                    <option value="EUR">Euro (EUR)</option>
                                    <option value="GBP">British Pound (GBP)</option>
                                    <option value="AUD">Australian Dollar (AUD)</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Employment Status</label>
                                <select class="form-select" name="employmentStatus" required>
                                    <option value="">Select Status</option>
                                    <option value="employed">Employed</option>
                                    <option value="self-employed">Self-Employed</option>
                                    <option value="student">Student</option>
                                    <option value="retired">Retired</option>
                                    <option value="unemployed">Unemployed</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Source of Income</label>
                                <select class="form-select" name="incomeSource" required>
                                    <option value="">Select Source</option>
                                    <option value="salary">Salary</option>
                                    <option value="business">Business Income</option>
                                    <option value="investments">Investments</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Initial Balance</label>
                                <div class="input-group">
                                    <span class="input-group-text">$</span>
                                    <input type="number" class="form-control" name="initial_balance" step="0.01" value="0.00">
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Account Status</label>
                                <select class="form-select" name="status" required>
                                    <option value="pending">Pending</option>
                                    <option value="active" selected>Active</option>
                                    <option value="suspended">Suspended</option>
                                    <option value="closed">Closed</option>
                                </select>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-outline-secondary" onclick="nextTab('profile-tab')">
                                <i class="fas fa-arrow-left"></i> Back
                            </button>
                            <button type="button" class="btn btn-primary" onclick="nextTab('security-tab')">
                                Continue <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 4: Security -->
                    <div class="tab-pane fade" id="security" role="tabpanel" aria-labelledby="security-tab">
                        <h5 class="mb-4">Security Setup</h5>
                        <div class="row g-3">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Username</label>
                                <input type="text" class="form-control" name="username" required 
                                       pattern="^[a-zA-Z0-9_]{4,20}$">
                                <small class="text-muted">4-20 characters, letters, numbers and underscore only</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Password</label>
                                <div class="input-group">
                                    <input type="password" class="form-control" name="password" id="password" required
                                           pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$">
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('password')">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <small class="text-muted">Minimum 8 characters, at least one letter and one number</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Confirm Password</label>
                                <div class="input-group">
                                    <input type="password" class="form-control" name="confirmPassword" id="confirmPassword" required>
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('confirmPassword')">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">PIN (4 digits)</label>
                                <input type="password" class="form-control" name="pin" id="pin" 
                                       pattern="\d{4}" maxlength="4" value="0000">
                                <small class="text-muted">Default: 0000 (User will be prompted to change)</small>
                            </div>
                        </div>

                        <div class="alert alert-info mt-4">
                            <i class="fas fa-info-circle"></i> Security codes (COT, IMF, TAX) will be automatically generated and sent to the user via email.
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-outline-secondary" onclick="nextTab('account-tab')">
                                <i class="fas fa-arrow-left"></i> Back
                            </button>
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-user-plus"></i> Create User Account
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function nextTab(tabId) {
    document.getElementById(tabId).click();
}

function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const icon = input.nextElementSibling.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.replace('fa-eye', 'fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.replace('fa-eye-slash', 'fa-eye');
    }
}

// Add form validation before submission
document.getElementById('addUserForm').addEventListener('submit', function(event) {
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirmPassword');
    
    if (password.value !== confirmPassword.value) {
        event.preventDefault();
        alert('Passwords do not match!');
        confirmPassword.focus();
    }
});

// Profile picture preview
document.getElementById('profilePicture').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        if (file.size > 5 * 1024 * 1024) {
            alert('File size too large. Maximum size is 5MB.');
            this.value = '';
            return;
        }

        if (!file.type.startsWith('image/')) {
            alert('Please select an image file.');
            this.value = '';
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('profilePreview').src = e.target.result;
        }
        reader.readAsDataURL(file);
    }
});
</script>

<?php
// Include the footer
include 'includes/footer.php';
?>
