<?php
/**
 * User Login 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: trade.php');
    exit;
}

$error = '';
$success = $_GET['registered'] ?? '' ? 'Registration successful! Please login.' : '';

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 {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        
        if (empty($email) || empty($password)) {
            $error = 'Please enter email and password.';
        } else {
            $user = dbFetch("SELECT * FROM users WHERE email = ?", [$email]);
            
            if ($user && password_verify($password, $user['password'])) {
                if ($user['status'] !== 'active') {
                    $error = 'Your account is not active (Status: "' . $user['status'] . '"). Please contact support.';
                } else {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_type'] = 'user';
                    $_SESSION['user_email'] = $user['email'];
                    $_SESSION['account_type'] = 'demo';
                    
                    dbQuery("UPDATE users SET last_login = NOW() WHERE id = ?", [$user['id']]);
                    header('Location: trade.php');
                    exit;
                }
            } else {
                $error = 'Invalid email or password.';
            }
        }
    }
}

// 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>Login - <?= 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;--blue:#1e88e5}
*{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}
.login-container{width:100%;max-width:420px}
.login-box{background:var(--bg3);border:1px solid var(--border);border-radius:16px;padding:32px}
.login-header{text-align:center;margin-bottom:32px}
.login-logo{font-size:2rem;font-weight:700;color:var(--green);margin-bottom:8px}
.login-title{font-size:1.5rem;font-weight:600;margin-bottom:4px}
.login-subtitle{color:var(--text2);font-size:.9rem}
.form-group{margin-bottom:20px}
.form-label{display:block;font-size:.85rem;color:var(--text2);margin-bottom:8px}
.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)}
.form-footer{display:flex;justify-content:space-between;align-items:center;font-size:.85rem;margin-bottom:24px}
.form-footer a{color:var(--green);text-decoration:none}
.btn-login{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-login:hover{opacity:.9}
.register-link{text-align:center;margin-top:24px;font-size:.9rem;color:var(--text2)}
.register-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)}
.alert-success{background:rgba(38,166,154,0.1);border:1px solid var(--green);color:var(--green)}
</style>
</head>
<body>
<div class="login-container">
<div class="login-box">
<div class="login-header">
<div class="login-logo">∫ <?= htmlspecialchars($siteName) ?></div>
<h1 class="login-title">Welcome Back</h1>
<p class="login-subtitle">Login to your trading account</p>
</div>

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

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

<div class="form-group">
<label class="form-label">Email Address</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">Password</label>
<div class="password-wrapper">
<input type="password" name="password" id="password" class="form-control" placeholder="Enter your password" required>
<button type="button" class="password-toggle" onclick="togglePassword('password', this)">
<i class="fas fa-eye"></i>
</button>
</div>
</div>

<div class="form-footer">
<label><input type="checkbox" name="remember"> Remember me</label>
<a href="#">Forgot password?</a>
</div>

<button type="submit" class="btn-login"><i class="fas fa-sign-in-alt"></i> Login</button>
</form>

<div class="register-link">
Don't have an account? <a href="register.php">Register now</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>
