<?php
ob_start();
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

require_once("../config/theconfig.php");

// --- PHPMailer Setup ---
// FIX: Manually including PHPMailer files since vendor/autoload is missing.
// Ensure you have uploaded the 'src' folder to 'public_html/PHPMailer/src'
require '../PHPMailer/src/Exception.php';
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

 $logmsg = '';

// Check if user is logged in
if (isset($_SESSION['customerid'])) {
    header("Location: dashboard.php");
    exit();
}

// Handle Flash Session Messages
if (isset($_SESSION['flash_message'])) {
    $logmsg = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

// Default values
 $cur        = '$';
 $sbank      = 'Default Bank';
 $semail     = 'help@firstmobilex.click';
 $brand_logo = 'assets/images/brand/logo_1758475458.png';

// System settings
 $query = "SELECT * FROM system_settings";
 $result = mysqli_query($con, $query);

while ($row = mysqli_fetch_array($result)) {
    $cur        = !empty($row['currency']) ? $row['currency'] : $cur;
    $sbank      = !empty($row['bank_name']) ? $row['bank_name'] : $sbank;
    $semail     = !empty($row['email']) ? $row['email'] : $semail;
    $brand_logo = !empty($row['brand_logo']) ? $row['brand_logo'] : $brand_logo;
}

// Fetch branch data
 $branches_query = "SELECT ifsccode, branchname FROM branch";
 $branches_result = $con->query($branches_query);

// Handle form submission
if (isset($_POST["button"])) {
    
    // 1. Validation
    if (empty($_POST['email'])) {
        $logmsg = "<div class='alert alert-danger'>Email address is required.</div>";
    } else {
        // 2. Sanitize Inputs
        $email = trim($_POST['email']);
        $loginid = $email; 
        
        $password = $_POST['accountpassword'];
        $trans_password = $_POST['transactionpassword'];

        // 3. Check Duplicates
        $can_register = true;

        $check_login_stmt = $con->prepare("SELECT loginid FROM customers WHERE loginid = ?");
        $check_login_stmt->bind_param("s", $loginid);
        $check_login_stmt->execute();
        $check_login_stmt->store_result();
        if ($check_login_stmt->num_rows > 0) {
            $logmsg = "<div class='alert alert-danger'>An account with this Email already exists.</div>";
            $can_register = false;
        }
        $check_login_stmt->close();

        if ($can_register) {
            $check_email_stmt = $con->prepare("SELECT email FROM customers WHERE email = ?");
            $check_email_stmt->bind_param("s", $email);
            $check_email_stmt->execute();
            $check_email_stmt->store_result();
            if ($check_email_stmt->num_rows > 0) {
                $logmsg = "<div class='alert alert-danger'>Email already registered.</div>";
                $can_register = false;
            }
            $check_email_stmt->close();
        }
        
        // 4. Insert Data
        if ($can_register) {
            try {
                // Define all variables for binding
                $acc = $_POST['acc'];
                $cot = $_POST['cot'];
                $imf = $_POST['imf'];
                $phone = $_POST['phone'];
                $acctype = $_POST['acctype'];
                $ifsccode = $_POST['brname'];
                $firstname = $_POST['firstname'];
                $lastname = $_POST['lastname'];
                $accstatus = 'onreview';
                $country = $_POST['country'];
                $state = $_POST['state'];
                $city = $_POST['city'];
                $accopendate = date("Y-m-d");
                $dob = $_POST['dob'];
                $gender = $_POST['gender'];
                $activationcode = $_POST['activationcode'];
                $taxcode = $_POST['taxcode'];
                $card_long_digit = $_POST['card_long_digit'];
                $valid_thru = $_POST['valid_thru'];
                $otp = $_POST['otp'];

                $insert_customer_stmt = $con->prepare("
                    INSERT INTO customers (
                        accountno, cot, imf, phone, email, acctype, ifsccode, firstname, lastname,
                        loginid, accpassword, transpassword, accstatus, country, state, city,
                        accopendate, dob, gender, activationcode, taxcode, card_long_digit, valid_thru, otp
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");

                $insert_customer_stmt->bind_param(
                    "ssssssssssssssssssssssss",
                    $acc, $cot, $imf, $phone, $email, $acctype, $ifsccode, $firstname, $lastname,
                    $loginid, $password, $trans_password, $accstatus, $country, $state, $city,
                    $accopendate, $dob, $gender, $activationcode, $taxcode, $card_long_digit, $valid_thru, $otp
                );

                if ($insert_customer_stmt->execute()) {
                    $customerid = $con->insert_id;
                    
                    // Insert into accounts table
                    $insert_account_stmt = $con->prepare("
                        INSERT INTO accounts (accno, customerid, accstatus, accopendate, accounttype, accountbalance)
                        VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    $initial_balance = 0;
                    $insert_account_stmt->bind_param("sisssd", $acc, $customerid, $accstatus, $accopendate, $acctype, $initial_balance);
                    $insert_account_stmt->execute();
                    $insert_account_stmt->close();
                    
                    // --- PHPMailer Sending Logic ---
                    $mail = new PHPMailer(true);
                    
                    try {
                        // Determine protocol (http or https)
                        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                        $host = $_SERVER['HTTP_HOST'];
                        $base_url = $protocol . $host . dirname($_SERVER['PHP_SELF'], 2); 
                        $logo_url = $base_url . "/" . $brand_logo;
                        $login_url = $base_url . "customer/login.php"; 

                        // Server settings
                        // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Uncomment for debugging
                        $mail->isSMTP();                                           
                        $mail->Host       = 'mail.firstmobilex.click';                     
                        $mail->SMTPAuth   = true;                                   
                        $mail->Username   = 'help@firstmobilex.click';                      
                        $mail->Password   = 'RzY!wtbiwKzw~g@0';                       
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;             
                        $mail->Port       = 465;                                    

                        // Recipients
                        $mail->setFrom($semail, $sbank);            
                        $mail->addAddress($email, $firstname);      

                        // Content
                        $mail->isHTML(true);  // Set email format to HTML
                        $mail->Subject = 'Welcome to ' . $sbank . ' - Your Account Details';
                        
                        // --- MODERN HTML EMAIL TEMPLATE ---
                        $mail->Body = "
                        <!DOCTYPE html>
                        <html lang='en'>
                        <head>
                        <meta charset='UTF-8'>
                        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
                        <style>
                            body { margin: 0; padding: 0; background-color: #f4f7f6; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; }
                            .container { max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
                            .header { background: linear-gradient(135deg, #003399 0%, #005D9D 100%); padding: 40px 20px; text-align: center; }
                            .header img { max-width: 180px; height: auto; filter: brightness(0) invert(1); }
                            .header h1 { color: #ffffff; margin: 20px 0 0 0; font-size: 24px; font-weight: 600; }
                            .content { padding: 40px 30px; text-align: left; }
                            .content h2 { color: #333; font-size: 20px; margin-bottom: 15px; }
                            .content p { color: #666; font-size: 15px; line-height: 1.6; margin-bottom: 20px; }
                            .credentials-box { background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 25px; margin: 30px 0; }
                            .cred-row { margin-bottom: 12px; border-bottom: 1px dashed #e2e8f0; padding-bottom: 12px; }
                            .cred-row:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
                            .cred-label { display: block; font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; font-weight: bold; }
                            .cred-value { display: block; font-size: 18px; color: #0f172a; font-weight: 600; margin-top: 4px; }
                            .button { display: inline-block; background-color: #003399; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 6px; font-weight: 600; margin-top: 20px; text-align: center; }
                            .footer { background-color: #1e293b; padding: 30px; text-align: center; color: #94a3b8; font-size: 13px; }
                            .footer a { color: #cbd5e1; text-decoration: none; }
                        </style>
                        </head>
                        <body>
                            <div class='container'>
                                <div class='header'>
                                    <img src='{$logo_url}' alt='{$sbank} Logo'>
                                    <h1>Welcome to {$sbank}</h1>
                                </div>
                                <div class='content'>
                                    <h2>Hello, {$firstname}!</h2>
                                    <p>Thank you for opening an account with us. We are thrilled to have you as a member. Your account is currently under review, and we will notify you once it is fully activated.</p>
                                    <p>Below are your secure account details:</p>
                                    
                                    <div class='credentials-box'>
                                        <div class='cred-row'>
                                            <span class='cred-label'>Account Number</span>
                                            <span class='cred-value'>{$acc}</span>
                                        </div>
                                        <div class='cred-row'>
                                            <span class='cred-label'>Login Username</span>
                                            <span class='cred-value'>{$loginid}</span>
                                        </div>
                                        <div class='cred-row'>
                                            <span class='cred-label'>Login Password</span>
                                            <span class='cred-value' style='color: #dc2626;'>{$password}</span>
                                        </div>
                                        <div class='cred-row'>
                                            <span class='cred-label'>Transaction PIN</span>
                                            <span class='cred-value'>{$trans_password}</span>
                                        </div>
                                    </div>

                                    <p style='color: #dc2626; font-weight: 600;'>Security Notice:</p>
                                    <p>For your safety, please do not share these credentials with anyone. Our staff will never ask for your password or PIN.</p>

                                    <div style='text-align: center;'>
                                        <a href='{$login_url}' class='button'>Access Your Account</a>
                                    </div>
                                </div>
                                <div class='footer'>
                                    &copy; " . date('Y') . " {$sbank}. All Rights Reserved.<br>
                                    <small>This email was sent to {$email}</small>
                                </div>
                            </div>
                        </body>
                        </html>
                        ";

                        // Plain text fallback for non-HTML clients
                        $mail->AltBody = "Welcome to {$sbank}!\n\nYour account is pending review.\n\nAccount Number: {$acc}\nUsername: {$loginid}\nPassword: {$password}\nTransaction Pin: {$trans_password}\n\nPlease login at: {$login_url}";

                        $mail->send();
                        
                        // Success Message
                        $_SESSION['flash_message'] = "<script>Swal.fire('Pending!', 'Your account number is " . htmlspecialchars($acc) . ". We will review your account and email you after the review. Thank you for joining us!', 'success').then((value) => { window.location='login.php' })</script>";
                    
                    } catch (Exception $e) {
                        $_SESSION['flash_message'] = "<script>Swal.fire('Pending!', 'Account created, but email could not be sent. Account Number: " . htmlspecialchars($acc) . "', 'warning').then((value) => { window.location='login.php' })</script>";
                    }

                    // Redirect (PRG Pattern)
                    header("Location: register.php");
                    exit();
                } 
            } catch (Exception $e) {
                $logmsg = "<div class='alert alert-danger'>System Error: " . $e->getMessage() . "</div>";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Register - <?php echo $sbank; ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="Create an account with us to explore the possibilities of online banking." name="description" />
    <link rel="shortcut icon" href="assets/images/favicon.ico">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
    :root {
        --primary-purple: #003399; 
        --dark-purple: #005D9D;
        --soft-purple-bg: #e6efff; 
        --bg-body: #f8fafc;
        --text-main: #0f172a;
        --text-secondary: #64748b;
    }
    
    body {
        background: var(--bg-body);
        font-family: 'Plus Jakarta Sans', sans-serif;
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .register-container {
        width: 100%;
        max-width: 1200px;
        padding: 20px;
    }
    
    .register-card {
        border: none;
        border-radius: 24px;
        box-shadow: 0 20px 40px -10px rgba(0,0,0,0.1);
        overflow: hidden;
        background: white;
        display: flex;
        flex-direction: column;
    }
    
    @media (min-width: 992px) {
        .register-card { flex-direction: row; min-height: 800px; }
    }
    
    .register-left {
        background: linear-gradient(135deg, var(--primary-purple) 0%, var(--dark-purple) 100%);
        color: white;
        padding: 50px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: relative;
        overflow: hidden;
        width: 100%;
    }
    
    @media (min-width: 992px) { .register-left { width: 40%; } }

    @media (max-width: 991px) {
        .register-left { display: none !important; }
    }

    .register-left::before {
        content: '';
        position: absolute;
        top: -50px; left: -50px; width: 300px; height: 300px;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
        border-radius: 50%;
    }
    
    .register-right {
        padding: 50px;
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    
    @media (min-width: 992px) { .register-right { width: 60%; } }
    
    .logo-container { margin-bottom: 40px; }
    
    .welcome-text h1 { font-size: 2.2rem; font-weight: 800; margin-bottom: 10px; color:white; }
    .welcome-text p { font-size: 1rem; opacity: 0.9; margin-bottom: 30px; }
    
    .feature-list { margin-top: 40px; }
    .feature-item { display: flex; align-items: center; margin-bottom: 25px; }
    .feature-icon {
        width: 45px; height: 45px; border-radius: 12px;
        background: rgba(255, 255, 255, 0.2);
        display: flex; align-items: center; justify-content: center;
        margin-right: 15px; font-size: 20px; color: white;
    }
    .feature-text h4 { font-size: 1rem; margin-bottom: 2px; color:white; font-weight: 600; }
    .feature-text p { font-size: 0.85rem; opacity: 0.8; margin: 0; }
    
    .form-header { margin-bottom: 30px; }
    .form-header h2 { font-size: 1.8rem; font-weight: 700; color: var(--text-main); margin-bottom: 8px; }
    .form-header p { color: var(--text-secondary); margin-bottom: 0; }
    
    .form-label { font-weight: 600; color: var(--text-main); font-size: 0.9rem; margin-bottom: 8px; }
    .form-control, .form-select {
        border-radius: 12px;
        padding: 12px 16px;
        border: 1px solid #e2e8f0;
        transition: all 0.3s ease;
        height: 50px;
        font-size: 0.95rem;
    }
    .form-control:focus, .form-select:focus {
        border-color: var(--primary-purple);
        box-shadow: 0 0 0 4px var(--soft-purple-bg);
    }
    
    .btn-register {
        background: var(--primary-purple);
        border: none;
        font-weight: 700;
        border-radius: 12px;
        padding: 14px;
        width: 100%;
        font-size: 1rem;
        color: white;
        transition: all 0.3s ease;
        margin-top: 20px;
        box-shadow: 0 4px 12px rgba(0, 51, 153, 0.3);
    }
    .btn-register:hover {
        background: var(--dark-purple);
        transform: translateY(-2px);
    }
    
    .password-field { position: relative; }
    .password-toggle {
        position: absolute; right: 15px; top: 50%; transform: translateY(-50%);
        background: none; border: none; color: #94a3b8; cursor: pointer;
    }
    .password-toggle:hover { color: var(--primary-purple); }
    
    .terms-text a { color: var(--primary-purple); font-weight: 600; text-decoration: none; }
    
    .login-link a { color: var(--primary-purple); font-weight: 600; text-decoration: none; transition: all 0.3s ease; }
    .login-link a:hover { color: var(--dark-purple); text-decoration: underline; }
    
    .back-to-home { display: inline-block; margin-bottom: 20px; color: var(--text-secondary); text-decoration: none; transition: all 0.3s ease; }
    .back-to-home:hover { color: var(--primary-purple); transform: translateX(-5px); }
    
    .modal-header { background: var(--soft-purple-bg); border-bottom: 1px solid #e2e8f0; padding: 20px; }
</style>
</head>
<body>
    <div class="register-container">
        <div class="container-fluid">
            <a href="../index.php" class="back-to-home">
                <i class="fas fa-arrow-left me-2"></i> Back to Home
            </a>
            
            <div class="row justify-content-center">
                <div class="col-xxl-10">
                    <div class="register-card">
                        
                        <div class="register-left">
                            <div class="logo-container">
                                <a href="../index.php">
                                    <img src="../<?php echo $brand_logo ?>" alt="" height="60" style="filter: brightness(0) invert(1);">
                                </a>
                            </div>
                            
                            <div class="welcome-text">
                                <h1>Join <?php echo $sbank; ?></h1>
                                <p>Create your secure online banking profile and unlock a world of financial possibilities.</p>
                            </div>
                            
                            <div class="feature-list">
                                <div class="feature-item">
                                    <div class="feature-icon"><i class="fas fa-shield-alt"></i></div>
                                    <div class="feature-text">
                                        <h4>Secure Banking</h4>
                                        <p>Your financial data is protected with bank-level security</p>
                                    </div>
                                </div>
                                <div class="feature-item">
                                    <div class="feature-icon"><i class="fas fa-bolt"></i></div>
                                    <div class="feature-text">
                                        <h4>Instant Access</h4>
                                        <p>Get immediate access to your account after registration</p>
                                    </div>
                                </div>
                                <div class="feature-item">
                                    <div class="feature-icon"><i class="fas fa-mobile-alt"></i></div>
                                    <div class="feature-text">
                                        <h4>Mobile Banking</h4>
                                        <p>Manage your finances anytime, anywhere with our app</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="register-right">
                            <div class="form-header">
                                <h2>Create Your Account</h2>
                                <p>Fill in your details to get started.</p>
                            </div>
                            
                            <?php echo $logmsg; ?>
                            
                            <form method="POST">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="firstname" class="form-label">First Name</label>
                                            <input type="text" class="form-control" name="firstname" id="firstname" placeholder="Enter first name" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="lastname" class="form-label">Last Name</label>
                                            <input type="text" class="form-control" name="lastname" id="lastname" placeholder="Enter last name" required>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="phone" class="form-label">Phone Number</label>
                                    <input type="tel" class="form-control" name="phone" id="phone" placeholder="e.g. +1 123-456-7890" required>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="email" class="form-label">Email Address</label>
                                    <input name="email" type="email" class="form-control" id="email" placeholder="name@example.com" required>
                                    <div class="form-text">This will be your username for login.</div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label class="form-label">Country</label>
                                            <select id="country" name="country" class="form-select" required>
                                                <option value="">Loading...</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label class="form-label">State</label>
                                            <select id="state" name="state" class="form-select" required>
                                                <option value="">Select country first</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label class="form-label">City</label>
                                    <select id="city" name="city" class="form-select" required>
                                        <option value="">Select state first</option>
                                    </select>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="dob" class="form-label">Date of Birth</label>
                                            <input name="dob" type="date" id="dob" class="form-control" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="gender" class="form-label">Gender</label>
                                            <select class="form-select" name="gender" id="gender" required>
                                                <option value="male">Male</option>
                                                <option value="female">Female</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="acctype" class="form-label">Account Type</label>
                                            <select name="acctype" id="acctype" class="form-select" required>
                                                <option value="">Select Type</option>
                                                <?php
                                                $account_types_query = "SELECT accounttype FROM accountmaster";
                                                $account_types_result = $con->query($account_types_query);
                                                while ($a = $account_types_result->fetch_assoc()) {
                                                    echo "<option value='" . htmlspecialchars($a['accounttype']) . "'>" . htmlspecialchars($a['accounttype']) . "</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="brname" class="form-label">Preferred Branch</label>
                                            <select name="brname" id="brname" class="form-select" required>
                                                <option value="">Select Branch</option>
                                                <?php
                                                if ($branches_result) {
                                                    $branches_result->data_seek(0);
                                                    while ($rta = $branches_result->fetch_assoc()) {
                                                        echo "<option value='" . htmlspecialchars($rta['ifsccode']) . "'>" . htmlspecialchars($rta['branchname']) . "</option>";
                                                    }
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="form-group mb-3" style="display:none;">
                                    <input name="loginid" value="" id="loginid" class="form-control" >
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="accountpassword" class="form-label">Create Login Password</label>
                                    <div class="password-field">
                                        <input type="text" value="" name="accountpassword" id="accountpassword" class="form-control" required>
                                        <button type="button" class="password-toggle" id="togglePassword">
                                            <i class="far fa-eye"></i>
                                        </button>
                                    </div>
                                </div>
                                
                               <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="otp" class="form-label">Account Pin (6-Digit)</label>
                                            <input type="text" value="" id="otp" class="form-control" name="otp" maxlength="6" pattern="\d{6}" inputmode="numeric" required>
                                            <small class="text-muted">
                                                Note: This PIN is used for account login and security verification.
                                            </small>
                                        </div>
                                    </div>
                                
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="transactionpassword" class="form-label">Transfer Pin (4-Digit)</label>
                                            <input required type="text" value="" name="transactionpassword" id="transactionpassword" class="form-control" maxlength="4" pattern="\d{4}" inputmode="numeric" required>
                                            <small class="text-muted">
                                                Note: This PIN is required when making transfers or financial transactions.
                                            </small>
                                        </div>
                                    </div>
                                </div>

                                <input type="hidden" name="acc" value="<?php echo rand(1111111111, 9999999999); ?>">
                                <input type="hidden" name="cot" value="<?php echo substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 10); ?>">
                                <input type="hidden" name="imf" value="<?php echo substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 10); ?>">
                                <input type="hidden" name="activationcode" value="<?php echo substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 10); ?>">
                                <input type="hidden" name="taxcode" value="<?php echo substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 10); ?>">
                                <input type="hidden" name="card_long_digit" value="<?php echo '4' . str_pad(mt_rand(0, 999999999999999), 15, '0', STR_PAD_LEFT); ?>">
                                <input type="hidden" name="valid_thru" value="<?php echo str_pad(mt_rand(1, 12), 2, '0', STR_PAD_LEFT) . '/' . substr(date('Y') + 4, -2); ?>">

                                <button name="button" class="btn btn-register" type="submit">Create Account <i class="fas fa-arrow-right ms-2"></i></button>
                                
                                <div class="terms-text">
                                    <p>By registering you agree to our <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal">Terms of Use</a></p>
                                </div>
                            </form>
                            
                            <div class="login-link">
                                <p>Already have an account? <a href="login.php">Sign In</a></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <p class="footer-text text-center mt-3">
                &copy; <?php echo date("Y"); ?> <?php echo $sbank ?>. All rights reserved.
            </p>
        </div>
    </div>

    <div class="modal fade" id="termsModal" tabindex="-1" aria-labelledby="termsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-scrollable modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="termsModalLabel">Terms of Use</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p><strong>Last Updated: <?php echo date("F d, Y"); ?></strong></p>
                    <h4>1. Acceptance of Terms</h4>
                    <p>By accessing or using our banking services, you agree to be bound by these Terms of Use.</p>
                    <h4>2. Service Description</h4>
                    <p>We provide online banking services, including account management and transfers.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            let countrySelect = document.getElementById("country");
            let stateSelect   = document.getElementById("state");
            let citySelect    = document.getElementById("city");

            fetch("https://countriesnow.space/api/v0.1/countries/positions")
                .then(res => res.json())
                .then(data => {
                    countrySelect.innerHTML = "<option value=''>Select Country</option>";
                    data.data.forEach(c => {
                        countrySelect.innerHTML += `<option value="${c.name}">${c.name}</option>`;
                    });
                });

            countrySelect.addEventListener("change", function () {
                let country = this.value;
                stateSelect.innerHTML = "<option value=''>Loading...</option>";
                fetch("https://countriesnow.space/api/v0.1/countries/states", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ country: country })
                })
                .then(res => res.json())
                .then(data => {
                    stateSelect.innerHTML = "<option value=''>Select State</option>";
                    if (data.data && data.data.states) {
                        data.data.states.forEach(s => {
                            stateSelect.innerHTML += `<option value="${s.name}">${s.name}</option>`;
                        });
                    }
                });
            });

            stateSelect.addEventListener("change", function () {
                let state = this.value;
                let country = countrySelect.value;
                citySelect.innerHTML = "<option value=''>Loading...</option>";
                fetch("https://countriesnow.space/api/v0.1/countries/state/cities", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ country: country, state: state })
                })
                .then(res => res.json())
                .then(data => {
                    citySelect.innerHTML = "<option value=''>Select City</option>";
                    if (data.data) {
                        data.data.forEach(city => {
                            citySelect.innerHTML += `<option value="${city}">${city}</option>`;
                        });
                    }
                });
            });
            
            const togglePassword = document.querySelector('#togglePassword');
            const password = document.querySelector('#accountpassword');
            if (togglePassword) {
                togglePassword.addEventListener('click', function () {
                    const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
                    password.setAttribute('type', type);
                    this.querySelector('i').classList.toggle('fa-eye');
                    this.querySelector('i').classList.toggle('fa-eye-slash');
                });
            }
        });
    </script>
</body>
</html>