<?php
require_once 'includes/config.php';
require_once 'includes/device_security.php';

if (isLoggedIn()) {
    header('Location: ' . SITE_URL . '/dashboard.php'); exit;
}

// Already blocked redirect
if (isset($_GET['blocked'])) {
    header('Location: ' . SITE_URL . '/device-blocked.php'); exit;
}

$error = '';
$deviceBlocked = false;
$deviceLimit   = false;
$whatsapp      = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitize($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember = isset($_POST['remember']);

    if ($username && $password) {
        $db = getDB();
        try { $db->exec("ALTER TABLE users ADD COLUMN remember_token VARCHAR(64) DEFAULT NULL"); } catch(Exception $e) {}
        $stmt = $db->prepare("SELECT * FROM users WHERE (username=? OR phone=? OR email=?) AND status='active' AND role!='admin'");
        $stmt->execute([$username,$username,$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            // ── Device Security Check ──
            $devCheck = checkDeviceLogin($user['id']);

            if (!$devCheck['ok']) {
                $whatsapp = getSetting('whatsapp_number') ?? '';
                if ($devCheck['blocked']) {
                    $deviceBlocked = true;
                    $error = 'এই ডিভাইস থেকে লগইন ব্লক করা হয়েছে।';
                } else {
                    $deviceLimit = true;
                    $error = 'সর্বোচ্চ ডিভাইস সীমা পেরিয়ে গেছে।';
                }
            } else {
                // Device OK — set session
                $_SESSION['user_id']       = $user['id'];
                $_SESSION['role']          = $user['role'];
                $_SESSION['name']          = $user['name'];
                $_SESSION['last_activity'] = time();
                $_SESSION['device_token']  = getDeviceToken();

                if ($remember) {
                    $token = bin2hex(random_bytes(32));
                    $db->prepare("UPDATE users SET remember_token=? WHERE id=?")->execute([$token,$user['id']]);
                    setcookie('remember_token', $token, time()+86400*30, '/', '', true, true);
                }
                header('Location: ' . SITE_URL . '/dashboard.php'); exit;
            }
        } else {
            $error = 'Wrong username or password!';
        }
    } else {
        $error = 'Please fill all fields!';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<title>Login - <?= SITE_NAME ?></title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Segoe UI',sans-serif;background:linear-gradient(135deg,#0d1f4e,#1a3c8f,#2856c8);min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px}
.card{background:white;border-radius:24px;padding:36px 30px;width:100%;max-width:380px;box-shadow:0 25px 60px rgba(0,0,0,0.3)}
.logo{text-align:center;margin-bottom:28px}
.logo-icon{width:70px;height:70px;background:linear-gradient(135deg,#0d1f4e,#1a3c8f);border-radius:20px;display:flex;align-items:center;justify-content:center;margin:0 auto 14px;font-size:28px}
.logo h1{font-size:24px;font-weight:800;color:#0d1f4e}
.logo h1 span{color:#f5a623}
.logo p{font-size:13px;color:#888;margin-top:4px}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7;padding:11px 14px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:16px;display:flex;align-items:center;gap:8px}
.fg{margin-bottom:14px}
.fg label{font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.4px;display:block;margin-bottom:6px}
.inp-wrap{position:relative}
.inp-wrap i{position:absolute;left:14px;top:50%;transform:translateY(-50%);color:#aaa;font-size:14px}
.inp-wrap input{width:100%;padding:13px 13px 13px 42px;border:2px solid #e8ecf4;border-radius:12px;font-size:15px;outline:none;transition:0.2s;color:#333}
.inp-wrap input:focus{border-color:#1a3c8f;box-shadow:0 0 0 3px rgba(26,60,143,0.1)}
.toggle-pw{position:absolute;right:14px;top:50%;transform:translateY(-50%);color:#aaa;cursor:pointer;font-size:14px;border:none;background:none}
.remember-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}
.remember-row label{display:flex;align-items:center;gap:8px;font-size:13px;color:#555;cursor:pointer;font-weight:600}
.remember-row input[type=checkbox]{width:17px;height:17px;cursor:pointer;accent-color:#1a3c8f}
.submit-btn{width:100%;padding:14px;background:linear-gradient(135deg,#1a3c8f,#2856c8);color:white;border:none;border-radius:12px;font-size:15px;font-weight:700;cursor:pointer;transition:0.2s;display:flex;align-items:center;justify-content:center;gap:8px}
.submit-btn:hover{opacity:0.95;transform:translateY(-1px)}
.admin-link{text-align:center;margin-top:20px;font-size:13px;color:#aaa}
.admin-link a{color:#1a3c8f;font-weight:700;text-decoration:none}
.divider{display:flex;align-items:center;gap:10px;margin:18px 0;color:#ddd;font-size:12px}
.divider::before,.divider::after{content:'';flex:1;height:1px;background:#e8ecf4}
</style>
</head>
<body>
<div class="card">
    <div class="logo">
        <div class="logo-icon">📱</div>
        <?php $_snp=explode(' ',trim(SITE_NAME),2); ?><h1><?= htmlspecialchars($_snp[0]) ?><?php if(isset($_snp[1])): ?> <span><?= htmlspecialchars($_snp[1]) ?></span><?php endif; ?></h1>
        <p>Welcome back! Please sign in.</p>
    </div>

    <?php if($deviceBlocked || $deviceLimit): ?>
    <div style="text-align:center;padding:10px 0">
        <div style="width:70px;height:70px;background:#fff5f5;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;font-size:32px">
            <?= $deviceBlocked ? '🚫' : '📱' ?>
        </div>
        <div style="font-size:17px;font-weight:800;color:#c53030;margin-bottom:8px">
            <?= $deviceBlocked ? 'ডিভাইস ব্লক করা হয়েছে' : 'ডিভাইস সীমা পূর্ণ' ?>
        </div>
        <div style="font-size:13px;color:#888;line-height:1.7;margin-bottom:20px">
            <?php if($deviceBlocked): ?>
            এই ডিভাইস থেকে লগইন করার অনুমতি নেই।<br>অ্যাডমিনের সাথে যোগাযোগ করুন।
            <?php else: ?>
            আপনার অ্যাকাউন্টে সর্বোচ্চ ডিভাইস সংখ্যা পূর্ণ হয়ে গেছে।<br>পুরনো ডিভাইস সরাতে অ্যাডমিনের সাথে যোগাযোগ করুন।
            <?php endif; ?>
        </div>
        <?php if($whatsapp): ?>
        <a href="https://wa.me/<?= preg_replace('/[^0-9]/','',$whatsapp) ?>?text=<?= urlencode('আমার একাউন্টে লগইন সমস্যা হচ্ছে। দয়া করে সাহায্য করুন।') ?>"
           target="_blank"
           style="display:inline-flex;align-items:center;gap:10px;background:#25D366;color:white;padding:14px 24px;border-radius:50px;font-size:14px;font-weight:700;text-decoration:none;box-shadow:0 4px 16px rgba(37,211,102,0.35)">
            <i class="fab fa-whatsapp" style="font-size:20px"></i> WhatsApp এ যোগাযোগ করুন
        </a>
        <div style="font-size:11px;color:#aaa;margin-top:10px"><?= htmlspecialchars($whatsapp) ?></div>
        <?php else: ?>
        <div style="background:#fff5f5;border-radius:10px;padding:12px;font-size:13px;color:#c53030">
            অ্যাডমিনের সাথে যোগাযোগ করুন
        </div>
        <?php endif; ?>
        <div style="margin-top:20px">
            <a href="login.php" style="font-size:13px;color:#1a3c8f;font-weight:600;text-decoration:none">← অন্য অ্যাকাউন্টে লগইন করুন</a>
        </div>
    </div>
    <?php elseif($error): ?>
    <div class="alert-err"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if(!$deviceBlocked && !$deviceLimit): ?>
    <form method="POST">
        <div class="fg">
            <label>Username / Phone</label>
            <div class="inp-wrap">
                <i class="fas fa-user"></i>
                <input type="text" name="username" placeholder="Enter username or phone" value="<?= htmlspecialchars($_POST['username']??'') ?>" required autofocus>
            </div>
        </div>
        <div class="fg">
            <label>Password</label>
            <div class="inp-wrap">
                <i class="fas fa-lock"></i>
                <input type="password" name="password" id="pwInput" placeholder="Enter password" required>
                <button type="button" class="toggle-pw" onclick="togglePw()"><i class="fas fa-eye" id="eyeIcon"></i></button>
            </div>
        </div>
        <div class="remember-row">
            <label>
                <input type="checkbox" name="remember" <?= isset($_POST['remember'])?'checked':'' ?>>
                Remember me (30 days)
            </label>
        </div>
        <button type="submit" class="submit-btn">
            <i class="fas fa-sign-in-alt"></i> Sign In
        </button>
    </form>
    <?php endif; ?>

    <div style="text-align:center;margin-top:16px">
        <a href="device-reset.php" style="font-size:13px;color:#e53e3e;font-weight:600;text-decoration:none">🔓 Device Reset</a>
    </div>
    <div style="text-align:center;margin-top:12px;font-size:13px;color:#aaa">
        Don't have an account? <a href="register.php" style="color:#1a3c8f;font-weight:700;text-decoration:none">Sign Up</a>
    </div>
</div>
<script>
function togglePw() {
    const inp = document.getElementById('pwInput');
    const ico = document.getElementById('eyeIcon');
    if (inp.type === 'password') { inp.type='text'; ico.className='fas fa-eye-slash'; }
    else { inp.type='password'; ico.className='fas fa-eye'; }
}
</script>
</body>
</html>
