<?php
/**
 * SmartForex Platform - Login & Registration Page
 * Location: public_html/login.php
 */
require_once __DIR__ . '/includes/functions.php';

// Agar user pehle se logged in hai toh dashboard par bhej dein
if (isset($_SESSION['user_id'])) {
    header("Location: " . SITE_URL . "/dashboard");
    exit;
}

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

// Form submission handle karein
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = sanitize($_POST['action'] ?? '');

    if ($action === 'register') {
        $username   = sanitize($_POST['username'] ?? '');
        $first_name = sanitize($_POST['first_name'] ?? '');
        $last_name  = sanitize($_POST['last_name'] ?? '');
        $email      = sanitize($_POST['email'] ?? '');
        $phone      = sanitize($_POST['phone'] ?? '');
        $address    = sanitize($_POST['address'] ?? '');
        $zip_code   = sanitize($_POST['zip_code'] ?? '');
        $password   = $_POST['password'] ?? '';

        if (!empty($username) && !empty($email) && !empty($password) && !empty($first_name) && !empty($last_name)) {
            // Check karein email ya username already exist toh nahi karta
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]);
            if ($stmt->rowCount() > 0) {
                $error = "Username or Email already exists!";
            } else {
                $hashed_password = password_hash($password, PASSWORD_BCRYPT);
                // Unified user registration vector compilation
                $stmt = $pdo->prepare("INSERT INTO users (username, first_name, last_name, email, phone, address, zip_code, password, balance, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0.00000000, 'active')");
                if ($stmt->execute([$username, $first_name, $last_name, $email, $phone, $address, $zip_code, $hashed_password])) {
                    $success = "Registration successful! Please login.";
                } else {
                    $error = "Something went wrong. Try again.";
                }
            }
        } else {
            $error = "Required core identity profiles missing structural metrics.";
        }
    } 
    
    if ($action === 'login') {
        $identity = sanitize($_POST['identity'] ?? '');
        $password = $_POST['password'] ?? '';

        if (!empty($identity) && !empty($password)) {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1");
            $stmt->execute([$identity, $identity]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                if ($user['status'] === 'banned' || $user['status'] === 'suspended') {
                    $error = "Your account has been suspended.";
                } else {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['user_role'] = 'user';
                    
                    header("Location: " . SITE_URL . "/dashboard");
                    exit;
                }
            } else {
                $error = "Invalid username/email or password.";
            }
        } else {
            $error = "All fields are required for login.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Login & Register - Bits Exchange</title>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Rajdhani:wght@500;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --dark: #050d1a; --darker: #020810; --card: #0a1628;
            --primary: #00d4ff; --text: #c8d8e8; --red: #ff3366; --green: #00ff88;
        }
        body {
            font-family: 'Rajdhani', sans-serif; background: var(--darker); color: var(--text);
            display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; padding: 20px box-sizing: border-box;
        }
        .auth-container {
            background: var(--card); border: 1px solid rgba(0,212,255,0.15); padding: 30px;
            border-radius: 12px; width: 100%; max-width: 440px; box-shadow: 0 0 20px rgba(0,212,255,0.05); box-sizing: border-box;
        }
        .auth-logo-frame {
            display: flex; justify-content: center; align-items: center; width: 100%; margin-bottom: 25px; min-height: 45px;
        }
        .auth-logo-frame img {
            height: auto; width: 105%; max-width: 290px; display: block; object-fit: contain;
        }
        .tabs { display: flex; margin-bottom: 20px; border-bottom: 1px solid rgba(200,216,232,0.1); }
        .tab { flex: 1; padding: 10px; text-align: center; cursor: pointer; font-weight: bold; font-family: 'Orbitron'; font-size: 14px; letter-spacing: 0.5px; }
        .tab.active { color: var(--primary); border-bottom: 2px solid var(--primary); }
        .form-group { margin-bottom: 15px; text-align: left; }
        .form-grid-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; font-size: 13px; color: #a4b8cc; }
        input {
            width: 100%; padding: 10px; background: var(--dark); border: 1px solid rgba(200,216,232,0.2);
            color: var(--text); border-radius: 4px; box-sizing: border-box; font-family: 'Rajdhani', sans-serif; font-size: 14px;
        }
        input:focus { border-color: var(--primary); outline: none; }
        button {
            width: 100%; padding: 12px; background: var(--primary); border: none; color: var(--darker);
            font-family: 'Orbitron', sans-serif; font-weight: bold; cursor: pointer; border-radius: 4px; margin-top: 10px; font-size: 14px; letter-spacing: 0.5px; transition: all 0.2s;
        }
        button:hover { opacity: 0.9; }
        .msg { padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center; font-weight: bold; font-size: 14px; }
        .error { background: rgba(255,51,102,0.1); color: var(--red); border: 1px solid var(--red); }
        .success { background: rgba(0,255,136,0.1); color: var(--green); border: 1px solid var(--green); }
        .hidden { display: none; }
    </style>
</head>
<body>

<div class="auth-container">
    <!-- RECONSTRUCTED LOGO STREAM INJECTION -->
    <div class="auth-logo-frame">
        <img src="uploads/logo.png" alt="Bits Exchange">
    </div>
    
 <!-- 🔥 SYNCED THREE-BUTTON TABS ENGINE WITH ACTIVE LINE HIGHLIGHT -->
                <div class="tabs" style="display: flex; border-bottom: 1px solid rgba(200,216,232,0.1); margin-bottom: 20px; width: 100%;">
                    <div class="tab active" id="login-tab" onclick="switchTab('login')" style="flex: 1; padding: 10px; text-align: center; cursor: pointer; font-weight: bold; font-family: 'Orbitron'; font-size: 14px;">LOGIN</div>
                    <div class="tab" id="register-tab" onclick="switchTab('register')" style="flex: 1; padding: 10px; text-align: center; cursor: pointer; font-weight: bold; font-family: 'Orbitron'; font-size: 14px;">REGISTER</div>
                    <div class="tab" id="demo-tab" onclick="document.querySelectorAll('.tab').forEach(t=>t.classList.remove('active')); this.classList.add('active'); setTimeout(() => { window.location.href='auth_demo.php'; }, 150);" style="flex: 1; padding: 10px; text-align: center; cursor: pointer; font-weight: bold; font-family: 'Orbitron'; font-size: 14px; color: #00ff88; transition: all 0.2s;">DEMO</div>
                </div>

    <?php if(!empty($error)): ?> <div class="msg error"><?= $error ?></div> <?php endif; ?>
    <?php if(!empty($success)): ?> <div class="msg success"><?= $success ?></div> <?php endif; ?>

    <!-- Login Form -->
    <form id="login-form" method="POST" action="">
        <input type="hidden" name="action" value="login">
        <div class="form-group">
            <label>Username or Email</label>
            <input type="text" name="identity" required>
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" name="password" required>
        </div>
        <button type="submit">ENTER DASHBOARD</button>
    </form>

    <!-- Extended Structural Registration Form Nodes -->
    <form id="register-form" method="POST" action="" class="hidden">
        <input type="hidden" name="action" value="register">
        
        <div class="form-grid-row">
            <div class="form-group">
                <label>First Name</label>
                <input type="text" name="first_name" required>
            </div>
            <div class="form-group">
                <label>Last Name</label>
                <input type="text" name="last_name" required>
            </div>
        </div>

        <div class="form-grid-row">
            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" required>
            </div>
            <div class="form-group">
                <label>Phone Number</label>
                <input type="text" name="phone" required>
            </div>
        </div>

        <div class="form-group">
            <label>Email Address</label>
            <input type="email" name="email" required>
        </div>

        <div class="form-grid-row">
            <div class="form-group" style="grid-column: span 1;">
                <label>Zip Code</label>
                <input type="text" name="zip_code" required>
            </div>
            <div class="form-group" style="grid-column: span 1;">
                <label>Password</label>
                <input type="password" name="password" required>
            </div>
        </div>

        <div class="form-group">
            <label>Residential Physical Address</label>
            <input type="text" name="address" required>
        </div>

        <button type="submit">CREATE ACCOUNT</button>
    </form>
</div>

<script>
    function switchTab(type) {
        if(type === 'login') {
            document.getElementById('login-form').classList.remove('hidden');
            document.getElementById('register-form').classList.add('hidden');
            document.getElementById('login-tab').classList.add('active');
            document.getElementById('register-tab').classList.remove('active');
        } else {
            document.getElementById('login-form').classList.add('hidden');
            document.getElementById('register-form').classList.remove('hidden');
            document.getElementById('login-tab').classList.remove('active');
            document.getElementById('register-tab').classList.add('active');
        }
    }
    
    <?php if(isset($_POST['action']) && $_POST['action'] === 'register' && !empty($error)): ?>
        switchTab('register');
    <?php endif; ?>
</script>
</body>
</html>