<?php
require_once __DIR__ . '/config/database.php';
$settings = getAllSettings($pdo);

if (isLoggedIn()) {
    if (isAdmin()) redirect(BASE_URL . '/admin/index.php');
    elseif (isInvestor()) redirect(BASE_URL . '/investor-dashboard.php');
    else redirect(BASE_URL . '/user-dashboard.php');
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';

    if (!$phone || !$password) {
        $error = 'সকল তথ্য প্রদান করুন।';
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE phone = ?");
        $stmt->execute([$phone]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['user_phone'] = $user['phone'];
            $_SESSION['user_address'] = $user['address'];
            $_SESSION['role'] = $user['role'];

            if ($user['role'] === 'admin') redirect(BASE_URL . '/admin/index.php');
            elseif ($user['role'] === 'investor') redirect(BASE_URL . '/investor-dashboard.php');
            else redirect(BASE_URL . '/user-dashboard.php');
        } else {
            $error = 'ফোন নম্বর বা পাসওয়ার্ড সঠিক নয়।';
        }
    }
}

include __DIR__ . '/includes/header.php';
?>

<div class="auth-page">
    <div class="auth-box">
        <h2><i class="fas fa-user-circle" style="color:var(--gold)"></i></h2>
        <h2>লগইন করুন</h2>
        <p class="subtitle">আপনার অ্যাকাউন্টে প্রবেশ করুন</p>

        <?php if ($error): ?>
            <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= e($error) ?></div>
        <?php endif; ?>
        <?php if (isset($_GET['registered'])): ?>
            <div class="alert alert-success"><i class="fas fa-check-circle"></i> নিবন্ধন সফল! এখন লগইন করুন।</div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group">
                <label class="form-label">মোবাইল নম্বর</label>
                <input type="tel" class="form-control" name="phone" placeholder="০১XXXXXXXXX" required value="<?= e($_POST['phone'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label class="form-label">পাসওয়ার্ড</label>
                <input type="password" class="form-control" name="password" placeholder="আপনার পাসওয়ার্ড" required>
            </div>
            <button type="submit" class="btn-primary">লগইন করুন</button>
        </form>

        <div class="auth-switch">
            অ্যাকাউন্ট নেই? <a href="<?= BASE_URL ?>/register.php">নিবন্ধন করুন</a>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
