<?php
require_once __DIR__ . '/includes/functions.php';

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

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

    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND status = 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id']         = $user['id'];
        $_SESSION['user_name']       = $user['name'];
        $_SESSION['user_role']       = $user['role'];
        $_SESSION['tab_permissions'] = json_decode($user['tab_permissions'] ?? '[]', true) ?: [];
        header('Location: dashboard.php');
        exit;
    } else {
        $error = 'Invalid email or password.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - Seder Core</title>
<link rel="icon" type="image/png" sizes="32x32" href="assets/img/favicon-32.png?v=5">
<link rel="icon" type="image/png" sizes="16x16" href="assets/img/favicon-16.png?v=5">
<link rel="apple-touch-icon" href="assets/img/apple-touch-icon.png?v=5">
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@600;700&family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/style.css?v=5">
</head>
<body>
<div class="login-page">
    <div class="login-card">
        <img src="assets/img/logo.png?v=5" alt="Seder Core" class="login-logo-img">
        <div class="logo-sub">Sign in to continue</div>

        <?php if ($error): ?>
        <div class="alert alert-danger"><?= icon('alert-circle') ?> <?= sanitize($error) ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group">
                <label>Email Address</label>
                <input type="email" name="email" required autofocus value="<?= sanitize($_POST['email'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" required>
            </div>
            <button type="submit" class="btn btn-primary btn-block">
                <?= icon('login') ?> Sign In
            </button>
        </form>

        <div class="divider"></div>
        <!--<p class="text-sm text-muted text-center" style="text-align:center;">-->
        <!--    Default: admin@stockapp.com / admin123<br>-->
        <!--    <em>(Please change this password after first login)</em>-->
        <!--</p>-->
    </div>
</div>
</body>
</html>