<?php
/**
 * User Registration Page - Fixed with Password Toggle
 */
require_once '../config/config.php';
// Lock file check removed by user request
require_once '../config/database.php';
require_once '../includes/functions.php';

// Already logged in?
if (isset($_SESSION['user_id']) && isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'user') {
    header('Location: dashboard.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST[CSRF_TOKEN_NAME] ?? '';
    if (!isset($_SESSION[CSRF_TOKEN_NAME]) || !hash_equals($_SESSION[CSRF_TOKEN_NAME], $token)) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $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'] ?? '';
        
        if (empty($firstName) || empty($email) || empty($password)) {
            $error = 'Please fill 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.';
        } else {
            $existing = dbFetch("SELECT id FROM users WHERE email = ?", [$email]);
            if ($existing) {
                $error = 'Email already registered. Please login.';
            } else {
                $hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
                $userId = 'U' . strtoupper(substr(md5(uniqid()), 0, 8));
                
                $newUserId = dbInsert('users', [
                    'user_id' => $userId,
                    'email' => $email,
                    'password' => $hashedPassword,
                    'first_name' => $firstName,
                    'last_name' => $lastName,
                    'phone' => $phone,
                    'status' => 'active',
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                
                if ($newUserId) {
                    // Create wallet
                    dbInsert('user_wallets', [
                        'user_id' => $newUserId,
                        'balance' => 0,
                        'demo_balance' => defined('DEMO_BALANCE') ? DEMO_BALANCE : 10000
                    ]);
                    
                    header('Location: login.php?registered=1');
                    exit;
                } else {
                    $error = 'Registration failed. Please try again.';
                }
            }
        }
    }
}

// Generate CSRF token
$_SESSION[CSRF_TOKEN_NAME] = bin2hex(random_bytes(32));
$siteName = defined('APP_NAME') ? APP_NAME : 'BinaryPro';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Register - <?= htmlspecialchars($siteName) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root{--bg:#0a0e17;--bg2:#12171f;--bg3:#1a1f2a;--text:#fff;--text2:#8b92a8;--border:#2a3344;--green:#26a69a;--red:#ef5350}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px}
.register-container{width:100%;max-width:480px}
.register-box{background:var(--bg3);border:1px solid var(--border);border-radius:16px;padding:32px}
.register-header{text-align:center;margin-bottom:32px}
.register-logo{font-size:2rem;font-weight:700;color:var(--green);margin-bottom:8px}
.register-title{font-size:1.5rem;font-weight:600;margin-bottom:4px}
.register-subtitle{color:var(--text2);font-size:.9rem}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:500px){.form-row{grid-template-columns:1fr}}
.form-group{margin-bottom:20px}
.form-label{display:block;font-size:.85rem;color:var(--text2);margin-bottom:8px}
.form-label .required{color:var(--red)}
.form-control{width:100%;padding:14px 16px;background:var(--bg2);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:1rem;outline:none;transition:border-color .2s}
.form-control:focus{border-color:var(--green)}
.password-wrapper{position:relative}
.password-wrapper .form-control{padding-right:50px}
.password-toggle{position:absolute;right:16px;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--text2);cursor:pointer;font-size:1.1rem;padding:4px}
.password-toggle:hover{color:var(--text)}
.btn-register{width:100%;padding:14px;background:var(--green);color:#fff;border:none;border-radius:10px;font-size:1rem;font-weight:600;cursor:pointer;transition:opacity .2s}
.btn-register:hover{opacity:.9}
.login-link{text-align:center;margin-top:24px;font-size:.9rem;color:var(--text2)}
.login-link a{color:var(--green);text-decoration:none;font-weight:500}
.alert{padding:12px 16px;border-radius:8px;margin-bottom:20px;font-size:.9rem}
.alert-error{background:rgba(239,83,80,0.1);border:1px solid var(--red);color:var(--red)}
</style>
</head>
<body>
<div class="register-container">
<div class="register-box">
<div class="register-header">
<div class="register-logo">∫ <?= htmlspecialchars($siteName) ?></div>
<h1 class="register-title">Create Account</h1>
<p class="register-subtitle">Start trading in minutes</p>
</div>

<?php if($error): ?><div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>

<form method="POST" action="">
<input type="hidden" name="<?= CSRF_TOKEN_NAME ?>" value="<?= $_SESSION[CSRF_TOKEN_NAME] ?>">

<div class="form-row">
<div class="form-group">
<label class="form-label">First Name <span class="required">*</span></label>
<input type="text" name="first_name" class="form-control" placeholder="First name" required value="<?= htmlspecialchars($_POST['first_name'] ?? '') ?>">
</div>
<div class="form-group">
<label class="form-label">Last Name</label>
<input type="text" name="last_name" class="form-control" placeholder="Last name" value="<?= htmlspecialchars($_POST['last_name'] ?? '') ?>">
</div>
</div>

<div class="form-group">
<label class="form-label">Email Address <span class="required">*</span></label>
<input type="email" name="email" class="form-control" placeholder="Enter your email" required value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
</div>

<div class="form-group">
<label class="form-label">Phone Number</label>
<input type="tel" name="phone" class="form-control" placeholder="Phone number" value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>">
</div>

<div class="form-group">
<label class="form-label">Password <span class="required">*</span></label>
<div class="password-wrapper">
<input type="password" name="password" id="password" class="form-control" placeholder="Min 6 characters" required>
<button type="button" class="password-toggle" onclick="togglePassword('password', this)">
<i class="fas fa-eye"></i>
</button>
</div>
</div>

<div class="form-group">
<label class="form-label">Confirm Password <span class="required">*</span></label>
<div class="password-wrapper">
<input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm password" required>
<button type="button" class="password-toggle" onclick="togglePassword('confirm_password', this)">
<i class="fas fa-eye"></i>
</button>
</div>
</div>

<button type="submit" class="btn-register"><i class="fas fa-user-plus"></i> Create Account</button>
</form>

<div class="login-link">
Already have an account? <a href="login.php">Login here</a>
</div>
</div>
</div>

<script>
function togglePassword(inputId, btn) {
    const input = document.getElementById(inputId);
    const icon = btn.querySelector('i');
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}
</script>
</body>
</html>
