<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mailer.php';

if (isset($_SESSION['user_id'])) {
    header("Location: /user/dashboard.php");
    exit;
}

$error = "";
$success = "";

// Supported currencies
$currencies = [
    'USD' => ['name' => 'US Dollar', 'symbol' => '$'],
    'EUR' => ['name' => 'Euro', 'symbol' => '€'],
    'GBP' => ['name' => 'British Pound', 'symbol' => '£'],
    'CAD' => ['name' => 'Canadian Dollar', 'symbol' => 'C$'],
    'AUD' => ['name' => 'Australian Dollar', 'symbol' => 'A$'],
    'JPY' => ['name' => 'Japanese Yen', 'symbol' => '¥'],
    'CNY' => ['name' => 'Chinese Yuan', 'symbol' => '¥'],
    'CHF' => ['name' => 'Swiss Franc', 'symbol' => 'CHF'],
    'ZAR' => ['name' => 'South African Rand', 'symbol' => 'R'],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $first_name = sanitizeInput($_POST['first_name'] ?? '');
    $last_name  = sanitizeInput($_POST['last_name'] ?? '');
    $email      = sanitizeInput($_POST['email'] ?? '');
    $phone      = sanitizeInput($_POST['phone'] ?? '');
    $password   = trim($_POST['password'] ?? '');
    $confirm    = trim($_POST['confirm_password'] ?? '');
    $address    = sanitizeInput($_POST['address'] ?? '');
    $city       = sanitizeInput($_POST['city'] ?? '');
    $zip_code   = sanitizeInput($_POST['zip_code'] ?? '');
    $state      = sanitizeInput($_POST['state'] ?? '');
    $country    = sanitizeInput($_POST['country'] ?? '');
    $account_type = sanitizeInput($_POST['account_type'] ?? 'savings');
    $currency   = sanitizeInput($_POST['currency'] ?? 'USD');

    // Profile photo
    $profile_photo = null;
    if (!empty($_FILES['profile_photo']['name'])) {
        $targetDir = __DIR__ . '/../assets/uploads/profiles/';
        if (!is_dir($targetDir)) mkdir($targetDir, 0755, true);
        $ext = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
        $filename = uniqid('profile_') . '.' . $ext;
        $targetFile = $targetDir . $filename;
        if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $targetFile)) {
            $profile_photo = '/assets/uploads/profiles/' . $filename;
        }
    }

    // Validation
    if ($first_name === "" || $last_name === "" || $email === "" || $password === "" || $confirm === "") {
        $error = "Please fill in all required fields.";
    } elseif (!isValidEmail($email)) {
        $error = "Invalid email format.";
    } elseif ($password !== $confirm) {
        $error = "Passwords do not match.";
    } else {
        // Check if email exists
        $stmtCheck = $conn->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
        if (!$stmtCheck) die("Prepare failed: " . $conn->error);
        $stmtCheck->bind_param("s", $email);
        $stmtCheck->execute();
        $stmtCheck->store_result();
        if ($stmtCheck->num_rows > 0) {
            $error = "Email already registered.";
            $stmtCheck->close();
        } else {
            $stmtCheck->close();

            // Insert User
            $hashed = hashPassword($password);
            $role = 'user';
            $status = 'active';
            $created_at = date('Y-m-d H:i:s');

            $stmtUser = $conn->prepare("
                INSERT INTO users
                (email, password, role, first_name, last_name, address, city, zip_code, state, country, phone, profile_photo, status, created_at, currency, account_type)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ");
            if (!$stmtUser) die("Prepare failed: " . $conn->error);

            $stmtUser->bind_param(
                "ssssssssssssssss",
                $email,
                $hashed,
                $role,
                $first_name,
                $last_name,
                $address,
                $city,
                $zip_code,
                $state,
                $country,
                $phone,
                $profile_photo,
                $status,
                $created_at,
                $currency,
                $account_type
            );

            if ($stmtUser->execute()) {
                $user_id = $stmtUser->insert_id;
                $stmtUser->close();

                // Create user account
                $account_number = generateAccountNumber($conn);
                createAccountForUser($conn, $user_id, $account_type, $currency, $account_number);

                // Auto-login token
                $auto_login_token = bin2hex(random_bytes(32));
                $expires = date("Y-m-d H:i:s", strtotime("+15 minutes"));

                $stmtToken = $conn->prepare("
                    INSERT INTO auto_login_tokens (user_id, token, expires_at, used)
                    VALUES (?, ?, ?, 0)
                ");
                if (!$stmtToken) die("Prepare failed: " . $conn->error);
                $stmtToken->bind_param("iss", $user_id, $auto_login_token, $expires);
                $stmtToken->execute();
                $stmtToken->close();

                // Send auto-login email
                sendAutoLoginEmail($email, $auto_login_token, $first_name, $last_name);

                $success = "Registration successful! Check your email for your secure login link.";
            } else {
                $error = "Database error: " . $stmtUser->error;
                $stmtUser->close();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lombard Odier Financial Bank Registration</title>
<style>
body {
    margin: 0;
    font-family: Arial, sans-serif;
    background: linear-gradient(135deg, #0f172a, #1e293b);
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
}
.register-container {
    width: 100%;
    max-width: 520px;
    background: #ffffff;
    padding: 40px 25px;
    border-radius: 16px;
    box-shadow: 0 20px 60px rgba(0,0,0,0.4);
    box-sizing: border-box;
}
.register-logo img {
    display: block;
    margin: 0 auto 20px auto;
    width: 120px;
}
h2 { text-align: center; color: #1e293b; }
.subtitle { text-align: center; color: #64748b; margin-bottom: 20px; }
form { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
input, select { padding: 10px; border: 1px solid #cbd5e1; border-radius: 8px; width: 100%; box-sizing: border-box; }
input[type="file"] { grid-column: span 2; }
button { grid-column: span 2; padding: 12px; background: #2563eb; color: white; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; }
.error, .success { grid-column: span 2; padding: 10px; border-radius: 8px; margin-bottom: 10px; }
.error { background: #fee2e2; color: #b91c1c; }
.success { background: #d1fae5; color: #065f46; text-align: center; }
.login-link { grid-column: span 2; text-align: center; }
</style>
</head>
<body>
<div class="register-container">
    <div class="register-logo">
        <img src="/assets/images/logo.png" alt="Logo">
    </div>
    <h2>Create Account</h2>
    <p class="subtitle">Secure Banking Registration</p>

    <?php if($error): ?>
        <div class="error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if($success): ?>
        <div class="success">
            <h3>✅ Registration Successful</h3>
            <p>Check your email for login link</p>
            <a href="/auth/login.php">Go to Login</a>
        </div>
    <?php endif; ?>

    <?php if(!$success): ?>
    <form method="POST" enctype="multipart/form-data">
        <input type="text" name="first_name" placeholder="First Name" required>
        <input type="text" name="last_name" placeholder="Last Name" required>
        <input type="email" name="email" placeholder="Email Address" required>
        <input type="text" name="phone" placeholder="Phone Number" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="password" name="confirm_password" placeholder="Confirm Password" required>
        <input type="text" name="address" placeholder="Address">
        <input type="text" name="city" placeholder="City">
        <input type="text" name="zip_code" placeholder="Zip Code">
        <input type="text" name="state" placeholder="State">
        <input type="text" name="country" placeholder="Country">
        <input type="file" name="profile_photo">
        <select name="account_type">
            <option value="savings">Savings</option>
            <option value="current">Current</option>
            <option value="business">Business</option>
        </select>
        <select name="currency">
            <?php foreach($currencies as $code => $info): ?>
                <option value="<?= $code ?>"><?= $info['name'] ?> (<?= $info['symbol'] ?>)</option>
            <?php endforeach; ?>
        </select>
        <button type="submit">Register</button>
        <div class="login-link">
            Already have an account? <a href="/auth/login.php">Login</a>
        </div>
    </form>
    <?php endif; ?>
</div>
</body>
</html>