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

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

$error = '';
$errorAllowHtml = false;
if (($_GET['reason'] ?? '') === 'another_device') {
    $error = 'You were signed out because this account was logged in from another device/browser.';
}

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

    // STEP 1: find which company this email belongs to (master DB)
    $stmt = $pdoMaster->prepare(
        "SELECT t.* FROM tenant_user_index i
         JOIN tenants t ON t.id = i.tenant_id
         WHERE i.email = ? AND t.status = 'active'"
    );
    $stmt->execute([$email]);
    $tenant = $stmt->fetch();

    if (!$tenant) {
        $error = 'Invalid email or password.';
    } elseif ($tenant['license_expiry'] && strtotime($tenant['license_expiry']) < strtotime(date('Y-m-d'))) {
        $error = 'Your company\'s license expired on ' . date('d M Y', strtotime($tenant['license_expiry'])) . '. Please contact your administrator to renew it.';
    } elseif ($tenant['edition'] !== APP_EDITION) {
        // This company is licensed for the OTHER edition - point them to the right URL.
        $otherLabel = $tenant['edition'] === 'limited' ? 'Limited Edition' : 'Full Edition';
        $otherUrl   = $tenant['edition'] === 'limited' ? OTHER_URL_LIMITED : OTHER_URL_FULL;
        $error = "Your company is licensed for the <strong>$otherLabel</strong>. Please sign in at "
                . '<a href="' . $otherUrl . '/login.php">' . $otherUrl . '</a>';
        $errorAllowHtml = true;
    } else {
        // STEP 2: connect to THAT company's own database and verify the password
        try {
            $tenantPdo = new PDO(
                "mysql:host=" . $tenant['db_host'] . ";dbname=" . $tenant['db_name'] . ";charset=utf8mb4",
                $tenant['db_user'],
                $tenant['db_pass'],
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
            );
            $ustmt = $tenantPdo->prepare("SELECT * FROM users WHERE email = ? AND status = 1");
            $ustmt->execute([$email]);
            $user = $ustmt->fetch();
        } catch (PDOException $e) {
            $user = null;
        }

        if ($user && password_verify($password, $user['password'])) {
            // Single-device login: issue a fresh token and overwrite the DB copy.
            // Any other browser/device already logged in as this user will now
            // fail its next enforceSingleSession() check and get signed out.
            $sessionToken = bin2hex(random_bytes(32));
            $tenantPdo->prepare("UPDATE users SET active_session_token = ?, last_login_at = NOW(), last_login_ip = ? WHERE id = ?")
                ->execute([$sessionToken, $_SERVER['REMOTE_ADDR'] ?? '', $user['id']]);

            // Store which company DB to use for the rest of this session
            $_SESSION['tenant_id']       = $tenant['id'];
            $_SESSION['tenant_db_host']  = $tenant['db_host'];
            $_SESSION['tenant_db_name']  = $tenant['db_name'];
            $_SESSION['tenant_db_user']  = $tenant['db_user'];
            $_SESSION['tenant_db_pass']  = $tenant['db_pass'];
            $_SESSION['company_name']    = $tenant['company_name'];

            $_SESSION['user_id']         = $user['id'];
            $_SESSION['user_name']       = $user['name'];
            $_SESSION['user_role']       = $user['role'];
            $_SESSION['tab_permissions'] = json_decode($user['tab_permissions'] ?? '[]', true) ?: [];
            $_SESSION['session_token']   = $sessionToken;
            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') ?> <?= $errorAllowHtml ? $error : 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>