<?php
require_once 'functions.php';

// Start session if not already started in functions.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (isLoggedIn()) {
    header('Location: dashboard.php');
    exit();
}

$error = '';
$success = '';

// Determine current step based on active session states
$step = isset($_SESSION['reg_otp_code']) ? 'otp_verification' : 'registration';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // --- STEP 1: INITIAL REGISTRATION SUBMISSION ---
    if (isset($_POST['action_register'])) {
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        $pin = $_POST['pin'] ?? '';
        $accountType = $_POST['account_type'] ?? 'savings';
        
        // Validation
        if (empty($firstName) || empty($lastName) || empty($email) || empty($password) || empty($pin)) {
            $error = 'Please fill in all required fields.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } elseif (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        } elseif ($password !== $confirmPassword) {
            $error = 'Passwords do not match.';
        } elseif (!preg_match('/^\d{4}$/', $pin)) {
            $error = 'Transaction PIN must be exactly 4 digits.';
        } else {
            $db = getDB();
            
            // Check if email exists
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->bind_param('s', $email);
            $stmt->execute();
            if ($stmt->get_result()->num_rows > 0) {
                $error = 'An account with this email already exists.';
            } else {
                // Generate secure 6-digit OTP code
                $otp = rand(100000, 999990);
                
                // Cache data to session temporarily until verification completes
                $_SESSION['reg_otp_code'] = $otp;
                $_SESSION['reg_user_data'] = [
                    'first_name'   => $firstName,
                    'last_name'    => $lastName,
                    'email'        => $email,
                    'phone'        => $phone,
                    'password'     => $password,
                    'pin'          => $pin,
                    'account_type' => $accountType
                ];
                
                // Send Verification Code via Email
                $subject = "Verification Code - " . SITE_NAME;
                $body = "<h2>Verify your Email Address</h2>
                         <p>Thank you for initiating your registration with " . SITE_NAME . ".</p>
                         <p>Your one-time registration authorization OTP code is: <strong style='font-size:22px; color:var(--primary); letter-spacing:2px;'>{$otp}</strong></p>
                         <p>Please enter this code on the registration page to finalize and secure your account.</p>";
                
                @sendMail($email, $subject, $body);
                
                $step = 'otp_verification';
            }
        }
    }
    
    // --- STEP 2: OTP VERIFICATION SUBMISSION ---
    elseif (isset($_POST['action_verify_otp'])) {
        $enteredOtp = trim($_POST['otp_code'] ?? '');
        
        if (empty($enteredOtp)) {
            $error = 'Please enter the verification code.';
        } elseif (!isset($_SESSION['reg_otp_code']) || (int)$enteredOtp !== (int)$_SESSION['reg_otp_code']) {
            $error = 'Invalid verification code. Please check and try again.';
        } else {
            // Retrieve data cache safely from user session
            $regData = $_SESSION['reg_user_data'];
            $db = getDB();
            
            // Double-check availability during processing block
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->bind_param('s', $regData['email']);
            $stmt->execute();
            if ($stmt->get_result()->num_rows > 0) {
                $error = 'An account with this email was processed during validation.';
                // Clear state
                unset($_SESSION['reg_otp_code'], $_SESSION['reg_user_data']);
                $step = 'registration';
            } else {
                // Generate absolute unique system account number
                $accountNumber = generateAccountNumber();
                while ($db->query("SELECT id FROM users WHERE account_number = '$accountNumber'")->num_rows > 0) {
                    $accountNumber = generateAccountNumber();
                }
                
                $hashedPassword = hashPassword($regData['password']);
                $hashedPin = password_hash($regData['pin'], PASSWORD_BCRYPT);
                
                // Save user record securely to database
                $stmt = $db->prepare("INSERT INTO users (account_number, password, email, first_name, last_name, phone, account_type, pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->bind_param('ssssssss', $accountNumber, $hashedPassword, $regData['email'], $regData['first_name'], $regData['last_name'], $regData['phone'], $regData['account_type'], $hashedPin);
                
                if ($stmt->execute()) {
                    $userId = $db->insert_id;
                    
                    // Create welcome internal notification
                    createNotification($userId, 'Welcome to ' . SITE_NAME, 'Your account has been created successfully. Your account number is ' . $accountNumber, 'success');
                    
                    // Send detailed final account details welcome email
                    $subject = 'Welcome to ' . SITE_NAME . ' - Your Account Details';
                    $body = "<h2>Welcome to " . SITE_NAME . ", {$regData['first_name']}!</h2>
                        <p>Your email address has been verified, and your account is active.</p>
                        <hr style='border:none; border-top:1px solid #eee; margin:15px 0;' />
                        <p><strong>Account Holder Name:</strong> {$regData['first_name']} {$regData['last_name']}</p>
                        <p><strong>Account Number:</strong> <span style='font-family:monospace; font-size:16px; font-weight:700;'>{$accountNumber}</span></p>
                        <p><strong>Account Type:</strong> " . ucfirst($regData['account_type']) . "</p>
                        <hr style='border:none; border-top:1px solid #eee; margin:15px 0;' />
                        <p>You can now sign into your electronic banking panel and manage your financial updates instantly.</p>";
                    
                    @sendMail($regData['email'], $subject, $body);
                    
                    $success = 'Account created successfully! Your account number is: ' . $accountNumber;
                    
                    // Flush validation session records
                    unset($_SESSION['reg_otp_code'], $_SESSION['reg_user_data']);
                    
                    // Redirect safely after 5 seconds to login landing page
                    header('Refresh: 5; URL=index.php');
                } else {
                    $error = 'An internal system error occurred. Please try again.';
                }
            }
        }
    }
    
    // --- OPTIONAL STEP: CANCEL OTP VIEW AND GO BACK ---
    elseif (isset($_POST['action_cancel_otp'])) {
        unset($_SESSION['reg_otp_code'], $_SESSION['reg_user_data']);
        $step = 'registration';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .otp-box-container {
            display: flex;
            justify-content: center;
            gap: 12px;
            margin: 20px 0;
        }
        .otp-digit-field {
            width: 45px;
            height: 50px;
            text-align: center;
            font-size: 24px;
            font-weight: 700;
            border: 2px solid var(--gray-300);
            border-radius: var(--border-radius);
            background: var(--white);
        }
        .otp-digit-field:focus {
            border-color: var(--primary);
            box-shadow: var(--shadow-sm);
            outline: none;
        }
    </style>
</head>
<body class="login-page">
    <div class="login-container" style="max-width: 520px;">
        <div class="login-card">
            <div class="login-logo">
                <img src="assets/images/logo.png" alt="<?php echo SITE_NAME; ?>">
                <?php if ($step === 'otp_verification'): ?>
                    <h1>Verify Email</h1>
                    <p>Enter the 6-digit code sent to your email box</p>
                <?php else: ?>
                    <h1>Create Account</h1>
                    <p>Join <?php echo SITE_NAME; ?> today</p>
                <?php endif; ?>
            </div>
            
            <?php if ($error): ?>
                <div class="alert alert-danger" style="margin-bottom: 20px;">
                    <span>⚠</span> <?php echo e($error); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success" style="margin-bottom: 20px;">
                    <span>✓</span> <?php echo e($success); ?>
                    <p style="margin-top: 8px; font-size: 13px; font-weight: 600;">Redirecting to sign-in page...</p>
                </div>
            <?php else: ?>
                
                <?php if ($step === 'otp_verification'): ?>
                    <form method="POST" action="">
                        <div class="form-group" style="text-align: center;">
                            <label class="form-label">Enter 6-Digit OTP Code</label>
                            <div class="otp-box-container">
                                <input type="text" class="otp-digit-field" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="assembleOtp()" required>
                                <input type="text" class="otp-digit-field" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="assembleOtp()" required>
                                <input type="text" class="otp-digit-field" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="assembleOtp()" required>
                                <input type="text" class="otp-digit-field" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="assembleOtp()" required>
                                <input type="text" class="otp-digit-field" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="assembleOtp()" required>
                                <input type="text" class="otp-digit-field" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="assembleOtp()" required>
                            </div>
                            <input type="hidden" name="otp_code" id="final-otp-code">
                        </div>
                        
                        <button type="submit" name="action_verify_otp" class="btn btn-primary btn-block" style="padding: 14px; margin-bottom: 12px;">
                            Verify & Activate Account
                        </button>
                        <button type="submit" name="action_cancel_otp" class="btn btn-outline-danger btn-block" style="padding: 10px; font-size: 13px;" formnovalidate>
                            ← Back to Form Modification
                        </button>
                    </form>
                    
                <?php else: ?>
                    <form method="POST" action="">
                        <input type="hidden" name="action_register" value="1">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                            <div class="form-group">
                                <label class="form-label">First Name *</label>
                                <input type="text" name="first_name" class="form-control" required value="<?php echo e($_POST['first_name'] ?? ''); ?>">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Last Name *</label>
                                <input type="text" name="last_name" class="form-control" required value="<?php echo e($_POST['last_name'] ?? ''); ?>">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Email Address *</label>
                            <input type="email" name="email" class="form-control" required value="<?php echo e($_POST['email'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Phone Number</label>
                            <input type="tel" name="phone" class="form-control" value="<?php echo e($_POST['phone'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Account Type *</label>
                            <select name="account_type" class="form-control" required>
                                <option value="savings" <?php echo ($_POST['account_type'] ?? '') === 'savings' ? 'selected' : ''; ?>>Savings Account</option>
                                <option value="checking" <?php echo ($_POST['account_type'] ?? '') === 'checking' ? 'selected' : ''; ?>>Checking Account</option>
                                <option value="business" <?php echo ($_POST['account_type'] ?? '') === 'business' ? 'selected' : ''; ?>>Business Account</option>
                            </select>
                        </div>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                            <div class="form-group">
                                <label class="form-label">Password *</label>
                                <input type="password" name="password" class="form-control" required minlength="6" placeholder="Min 6 characters">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Confirm Password *</label>
                                <input type="password" name="confirm_password" class="form-control" required>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">4-Digit Transaction PIN *</label>
                            <div class="pin-inputs" style="margin: 12px 0;">
                                <input type="password" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="combinePin()" required>
                                <input type="password" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="combinePin()" required>
                                <input type="password" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="combinePin()" required>
                                <input type="password" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" oninput="combinePin()" required>
                            </div>
                            <input type="hidden" name="pin" id="combined-pin">
                            <p style="font-size: 11px; color: var(--gray); margin-top: 4px;">This PIN will be required for all transactions.</p>
                        </div>
                        
                        <button type="submit" class="btn btn-primary btn-block" style="padding: 14px;">
                            Get Verification Code
                        </button>
                    </form>
                <?php endif; ?>
                
            <?php endif; ?>
            
            <div style="text-align: center; margin-top: 24px; padding-top: 24px; border-top: 1px solid var(--gray-200);">
                <p style="font-size: 13px; color: var(--gray);">
                    Already have an account? <a href="index.php" style="color: var(--primary); font-weight: 700;">Sign In</a>
                </p>
            </div>
        </div>
    </div>
    
    <script src="assets/js/main.js"></script>
    <script>
        // Setup focus loops for multi-box styling configs
        document.addEventListener('DOMContentLoaded', function() {
            const boxes = document.querySelectorAll('.otp-digit-field');
            boxes.forEach((box, index) => {
                box.addEventListener('keyup', (e) => {
                    if (e.key >= 0 && e.key <= 9) {
                        if (boxes[index + 1]) boxes[index + 1].focus();
                    } else if (e.key === 'Backspace') {
                        if (boxes[index - 1]) boxes[index - 1].focus();
                    }
                });
            });
        });

        function assembleOtp() {
            const boxes = document.querySelectorAll('.otp-digit-field');
            let code = '';
            boxes.forEach(box => code += box.value);
            document.getElementById('final-otp-code').value = code;
        }

        function combinePin() {
            const inputs = document.querySelectorAll('.pin-input');
            let pin = '';
            inputs.forEach(input => pin += input.value);
            document.getElementById('combined-pin').value = pin;
        }
    </script>
</body>
</html>