<?php
require_once __DIR__ . '/../bootstrap.php';
ym_require('src/lib/auth.php');
ym_require('src/lib/helpers.php');
ym_require('src/lib/i18n.php');
ym_require('src/lib/topbar.php');
ym_require('src/lib/vessel_context.php');
ym_require('src/lib/vessel_selection.php');
ym_require('src/lib/db.php');
ym_require('src/services/VesselAdminService.php');
ym_require('src/services/PermissionService.php');
ym_require('src/services/ModuleService.php');
ym_require('src/services/OrganizationService.php');

require_login();

$user = current_user();
$userId = (int)$user['id'];

$userVessels = VesselAdminService::getVesselsForUser($userId);
usort($userVessels, static function (array $a, array $b): int {
    return strcasecmp((string)$a['vessel_name'], (string)$b['vessel_name']);
});

$userOrganizations = OrganizationService::getOrganizationsForUser($userId);
usort($userOrganizations, static function (array $a, array $b): int {
    return strcasecmp((string)$a['org_name'], (string)$b['org_name']);
});

$directOrgRolesByOrgId = [];

$orgIds = array_values(array_unique(array_map(
    static fn(array $org): int => (int)$org['id'],
    $userOrganizations
)));

if (!empty($orgIds)) {
    $placeholders = implode(',', array_fill(0, count($orgIds), '?'));

    $stmt = platform_db()->prepare(
        "SELECT organization_id, org_role
         FROM organization_users
         WHERE user_id = ?
           AND is_active = 1
           AND organization_id IN ($placeholders)"
    );

    $params = array_merge([$userId], $orgIds);
    $stmt->execute($params);

    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $directOrgRolesByOrgId[(int)$row['organization_id']] = (string)$row['org_role'];
    }
}

$organizationIndex = [];
foreach ($userOrganizations as $org) {
    $organizationIndex[(int)$org['id']] = $org;
}

$organizationTree = [];
foreach ($userOrganizations as $org) {
    $orgId = (int)$org['id'];
    $parentId = (int)($org['parent_organization_id'] ?? 0);

    if ($parentId > 0 && isset($organizationIndex[$parentId])) {
        if (!isset($organizationTree[$parentId])) {
            $organizationTree[$parentId] = [];
        }
        $organizationTree[$parentId][] = $org;
    }
}

$rootOrganizations = [];
foreach ($userOrganizations as $org) {
    $parentId = (int)($org['parent_organization_id'] ?? 0);

    if ($parentId <= 0 || !isset($organizationIndex[$parentId])) {
        $rootOrganizations[] = $org;
    }
}

usort($rootOrganizations, static function (array $a, array $b): int {
    return strcasecmp((string)$a['org_name'], (string)$b['org_name']);
});

foreach ($organizationTree as &$children) {
    usort($children, static function (array $a, array $b): int {
        return strcasecmp((string)$a['org_name'], (string)$b['org_name']);
    });
}
unset($children);

$vesselsByOrganization = [];
foreach ($userVessels as $vessel) {
    $orgId = (int)($vessel['organization_id'] ?? 0);
    if (!isset($vesselsByOrganization[$orgId])) {
        $vesselsByOrganization[$orgId] = [];
    }
    $vesselsByOrganization[$orgId][] = $vessel;
}

foreach ($vesselsByOrganization as &$vesselsInOrg) {
    usort($vesselsInOrg, static function (array $a, array $b): int {
        return strcasecmp((string)$a['vessel_name'], (string)$b['vessel_name']);
    });
}
unset($vesselsInOrg);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vessel_id'])) {
    $requestedVesselId = (int)$_POST['vessel_id'];

    if (PermissionService::userMayViewVessel($userId, $requestedVesselId)) {
        set_selected_vessel_id($requestedVesselId);
    }

    header('Location: /dashboard.php');
    exit;
}

$selectedVesselId = get_selected_vessel_id();
$currentVessel = null;

foreach ($userVessels as $v) {
    if ($selectedVesselId && (int)$v['id'] === (int)$selectedVesselId) {
        $currentVessel = $v;
        break;
    }
}

if (!$currentVessel && !empty($userVessels)) {
    $currentVessel = $userVessels[0];
    set_selected_vessel_id((int)$currentVessel['id']);
}

$isSuperadmin = current_user_is_superadmin();

$currentOrgRole = null;
$modules = [];
$visibleAdminUsers = $isSuperadmin;
$visibleOrganizationAdmin = $isSuperadmin;
$visibleModuleCatalog = $isSuperadmin;
$visibleVesselAdmin = false;

if ($currentVessel) {
    $currentOrgRole = $directOrgRolesByOrgId[(int)$currentVessel['organization_id']] ?? null;

    $modules = ModuleService::getModulesForVessel((int)$currentVessel['id']);

    $mayManageCurrentVessel = $isSuperadmin
        || PermissionService::userMayManageVessel($userId, (int)$currentVessel['id']);

    $visibleVesselAdmin = $mayManageCurrentVessel;
}
?>
<!DOCTYPE html>
<html lang="<?= e(current_language()) ?>">
<head>
    <meta charset="utf-8">
    <title><?= t('nav.dashboard', 'Dashboard') ?> - Yachtmemory</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php render_app_head_assets();  ?>
<?php render_topbar_styles(); ?>

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            background: #f4f6f8;
            color: #1f2a36;
        }

        main {
            padding: 24px;
            max-width: 1700px;
            margin: 0 auto;
        }

        .section-title {
            margin: 0 0 12px 0;
            font-size: 22px;
        }

        .section-subtitle {
            color: #5d6a75;
            margin: 0 0 18px 0;
        }

        .grid-ops {
            display: grid;
            grid-template-columns: repeat(6, minmax(220px, 1fr));
            gap: 16px;
            margin-bottom: 30px;
        }

        .grid-admin-mixed {
            display: grid;
            grid-template-columns: repeat(4, minmax(220px, 1fr));
            gap: 16px;
            margin-bottom: 30px;
        }

        .card {
            border-radius: 10px;
            padding: 18px;
            box-shadow: 0 2px 8px rgba(0,0,0,.08);
            min-height: 180px;
        }

        .card h3 {
            margin-top: 0;
            margin-bottom: 12px;
        }

        .card-ops {
            background: #ffffff;
        }

        .card-vessel-admin {
            background: #f3f7fb;
        }

        .card-masterdata {
            background: #eaf1f8;
        }

        .muted {
            color: #5d6a75;
        }

        .roles span {
            display: inline-block;
            background: #e8eef5;
            border-radius: 999px;
            padding: 5px 10px;
            margin: 4px 6px 0 0;
            font-size: 13px;
        }

        .vessel-search {
            margin-bottom: 12px;
        }

        .vessel-search input {
            width: 100%;
            padding: 9px 10px;
            border: 1px solid #ccd5df;
            border-radius: 8px;
            box-sizing: border-box;
            font: inherit;
        }

        .vessel-list-wrap {
            max-height: 320px;
            overflow-y: auto;
            padding-right: 4px;
        }

        .vessel-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .vessel-list li {
            margin: 0 0 8px 0;
        }

        .vessel-list form {
            margin: 0;
        }

        .vessel-list button {
            width: 100%;
            text-align: left;
            border: 1px solid #d7dfe8;
            background: #fff;
            border-radius: 8px;
            padding: 10px 12px;
            cursor: pointer;
            font: inherit;
        }

        .vessel-list button.active {
            background: #dde9f5;
            border-color: #8aa7c4;
            font-weight: bold;
        }

        .vessel-list .vessel-key {
            display: block;
            font-size: 12px;
            color: #5d6a75;
            margin-top: 3px;
        }

        .vessel-empty {
            color: #5d6a75;
            font-size: 14px;
            padding: 8px 0;
        }

        .kv p {
            margin: 8px 0;
        }

        ul.module-list {
            padding-left: 18px;
            margin: 0;
        }

        ul.module-list li {
            margin-bottom: 8px;
        }

        .section-block {
            margin-bottom: 30px;
        }

        @media (max-width: 1500px) {
            .grid-ops {
                grid-template-columns: repeat(3, minmax(220px, 1fr));
            }

            .grid-admin-mixed {
                grid-template-columns: repeat(2, minmax(240px, 1fr));
            }
        }

        @media (max-width: 900px) {
            .grid-ops,
            .grid-admin-mixed {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
<?php
render_topbar([
    ['href' => '/account.php', 'label' => t('nav.account', 'Mein Konto')],
    ['href' => '/logout.php', 'label' => t('nav.logout', 'Abmelden')],
], $currentVessel['vessel_name'] ?? null, true);
?>



<main>
    <section class="section-block">
        <h2 class="section-title"><?= t('dashboard.operations_title', 'Schiffsbetrieb') ?></h2>
        <p class="section-subtitle">
            <?= t('dashboard.operations_subtitle', 'Benutzerkontext, Schiffe, Rollen, Module und Zugang zum aktiven Schiffsdashboard.') ?>
        </p>

        <div class="grid-ops">
            <div class="card card-ops">
                <h3><?= t('dashboard.user_context', 'Eingeloggter Benutzer') ?></h3>
                <div class="kv">
                    <p><strong><?= t('users.name', 'Name') ?>:</strong> <?= e($user['display_name'] ?: $user['username']) ?></p>
                    <p><strong><?= t('users.email', 'E-Mail') ?>:</strong> <?= e($user['email']) ?></p>
                    <p><strong><?= t('users.global_role', 'Globale Rolle') ?>:</strong> <?= e(ym_role_label($user['global_role'] ?? 'user')) ?></p>
                    <p><strong><?= t('dashboard.organization_role', 'Organisationsrolle') ?>:</strong> <?= $currentOrgRole ? e(ym_role_label($currentOrgRole)) : '—' ?></p>
                    <p><strong><?= t('users.language', 'Sprache') ?>:</strong> <?= e($user['ui_language'] ?? 'de') ?></p>
                </div>
            </div>

            <div class="card card-ops">
                <h3><?= t('dashboard.organizations_short', 'Organisationen') ?></h3>

                <?php if ($rootOrganizations): ?>
                    <div class="vessel-list-wrap">
                        <ul class="vessel-list">
                            <?php foreach ($rootOrganizations as $org): ?>
                                <li>
                                    <div style="border:1px solid #d7dfe8; background:#fff; border-radius:8px; padding:10px 12px;">
                                        <strong><?= e($org['org_name']) ?></strong>
                                        <span class="vessel-key"><?= e($org['org_key']) ?></span>
                                        <span class="vessel-key">
                                            <?= e($org['org_type']) ?>
                                            <?php
                                            $directRole = $directOrgRolesByOrgId[(int)$org['id']] ?? null;
                                            if ($directRole && $directRole !== 'superadmin'):
                                            ?>
                                                — <?= e(ym_role_label($directRole)) ?>
                                            <?php endif; ?>
                                        </span>

                                        <?php if (!empty($organizationTree[(int)$org['id']])): ?>
                                            <div style="margin-top:10px; padding-left:14px; border-left:3px solid #dde5ee;">
                                                <?php foreach ($organizationTree[(int)$org['id']] as $child): ?>
                                                    <div style="margin-bottom:8px;">
                                                        <strong><?= e($child['org_name']) ?></strong>
                                                        <span class="vessel-key"><?= e($child['org_key']) ?></span>
                                                        <span class="vessel-key">
                                                            <?= e($child['org_type']) ?>
                                                            <?php
                                                            $childRole = $directOrgRolesByOrgId[(int)$child['id']] ?? null;
                                                            if ($childRole && $childRole !== 'superadmin'):
                                                            ?>
                                                                — <?= e(ym_role_label($childRole)) ?>
                                                            <?php endif; ?>
                                                        </span>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php else: ?>
                    <p class="muted"><?= t('dashboard.no_assigned_organizations', 'Diesem Benutzer sind aktuell keine Organisationen zugeordnet.') ?></p>
                <?php endif; ?>
            </div>

            <div class="card card-ops">
                <h3><?= t('dashboard.assigned_vessels', 'Zugeordnete Schiffe') ?></h3>

                <?php if ($userVessels): ?>
                    <div class="vessel-search">
                        <input
                            type="text"
                            id="vesselSearch"
                            placeholder="<?= e(t('dashboard.search_vessels', 'Schiffe suchen...')) ?>"
                            oninput="filterVesselList()"
                        >
                    </div>

                    <div class="vessel-list-wrap">
                        <ul class="vessel-list" id="vesselList">
                            <?php foreach ($rootOrganizations as $rootOrg): ?>
                                <?php
                                $rootOrgId = (int)$rootOrg['id'];
                                $rootHasChildren = !empty($organizationTree[$rootOrgId]);
                                $rootHasDirectVessels = !empty($vesselsByOrganization[$rootOrgId]);
                                ?>

                                <?php if (!$rootHasChildren && !$rootHasDirectVessels): ?>
                                    <?php continue; ?>
                                <?php endif; ?>

                                <li class="vessel-item-group">
                                    <div style="border:1px solid #d7dfe8; background:#f9fbfd; border-radius:8px; padding:10px 12px; margin-bottom:8px;">
                                        <strong><?= e($rootOrg['org_name']) ?></strong>
                                        <span class="vessel-key"><?= e($rootOrg['org_key']) ?> — <?= e($rootOrg['org_type']) ?></span>

                                        <?php if ($rootHasDirectVessels): ?>
                                            <div style="margin-top:10px;">
                                                <?php foreach ($vesselsByOrganization[$rootOrgId] as $vessel): ?>
                                                    <div
                                                        class="vessel-item"
                                                        data-search="<?= e(mb_strtolower(
                                                            ($vessel['vessel_name'] ?? '') . ' ' .
                                                            ($vessel['vessel_key'] ?? '') . ' ' .
                                                            ($rootOrg['org_name'] ?? '')
                                                        )) ?>"
                                                        style="margin-bottom:8px;"
                                                    >
                                                        <form method="post">
                                                            <input type="hidden" name="vessel_id" value="<?= (int)$vessel['id'] ?>">
                                                            <button
                                                                type="submit"
                                                                class="<?= ($currentVessel && (int)$vessel['id'] === (int)$currentVessel['id']) ? 'active' : '' ?>"
                                                            >
                                                                <?= e($vessel['vessel_name']) ?>
                                                                <span class="vessel-key"><?= e($vessel['vessel_key']) ?></span>
                                                            </button>
                                                        </form>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>

                                        <?php if ($rootHasChildren): ?>
                                            <div style="margin-top:10px; padding-left:14px; border-left:3px solid #dde5ee;">
                                                <?php foreach ($organizationTree[$rootOrgId] as $childOrg): ?>
                                                    <?php
                                                    $childOrgId = (int)$childOrg['id'];
                                                    $childVessels = $vesselsByOrganization[$childOrgId] ?? [];
                                                    ?>

                                                    <?php if (empty($childVessels)): ?>
                                                        <?php continue; ?>
                                                    <?php endif; ?>

                                                    <div style="margin-bottom:10px;">
                                                        <strong><?= e($childOrg['org_name']) ?></strong>
                                                        <span class="vessel-key"><?= e($childOrg['org_key']) ?> — <?= e($childOrg['org_type']) ?></span>

                                                        <div style="margin-top:8px;">
                                                            <?php foreach ($childVessels as $vessel): ?>
                                                                <div
                                                                    class="vessel-item"
                                                                    data-search="<?= e(mb_strtolower(
                                                                        ($vessel['vessel_name'] ?? '') . ' ' .
                                                                        ($vessel['vessel_key'] ?? '') . ' ' .
                                                                        ($childOrg['org_name'] ?? '') . ' ' .
                                                                        ($rootOrg['org_name'] ?? '')
                                                                    )) ?>"
                                                                    style="margin-bottom:8px;"
                                                                >
                                                                    <form method="post">
                                                                        <input type="hidden" name="vessel_id" value="<?= (int)$vessel['id'] ?>">
                                                                        <button
                                                                            type="submit"
                                                                            class="<?= ($currentVessel && (int)$vessel['id'] === (int)$currentVessel['id']) ? 'active' : '' ?>"
                                                                        >
                                                                            <?= e($vessel['vessel_name']) ?>
                                                                            <span class="vessel-key"><?= e($vessel['vessel_key']) ?></span>
                                                                        </button>
                                                                    </form>
                                                                </div>
                                                            <?php endforeach; ?>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </li>
                            <?php endforeach; ?>
                        </ul>

                        <div id="vesselEmptyState" class="vessel-empty" style="display:none;">
                            <?= e(t('dashboard.no_vessels_match', 'Keine Schiffe gefunden.')) ?>
                        </div>
                    </div>
                <?php else: ?>
                    <p class="muted"><?= t('dashboard.no_assigned_vessels', 'Diesem Benutzer sind aktuell keine Schiffe zugeordnet.') ?></p>
                <?php endif; ?>
            </div>

            <div class="card card-ops">
                <h3><?= t('dashboard.current_vessel', 'Aktuelles Schiff') ?></h3>
                <?php if ($currentVessel): ?>
                    <div class="kv">
                        <p><strong><?= t('vessel.name', 'Schiffsname') ?>:</strong> <?= e($currentVessel['vessel_name']) ?></p>
                        <p><strong><?= t('vessel.key', 'Vessel Key') ?>:</strong> <?= e($currentVessel['vessel_key']) ?></p>
                        <p><strong><?= t('vessel.organization', 'Organisation') ?>:</strong> <?= e($currentVessel['org_name'] ?? '') ?></p>
                        <p><strong><?= t('vessel.telemetry_db', 'Telemetry-Datenbank') ?>:</strong> <?= e($currentVessel['telemetry_db_name'] ?? '') ?></p>
                    </div>

                    <div style="margin-top:12px;">
                        <strong><?= t('dashboard.organization_role', 'Organisationsrolle') ?>:</strong>
                        <?php if ($currentOrgRole): ?>
                            <div class="roles" style="margin-top:6px;">
                                <span><?= e(ym_role_label($currentOrgRole)) ?></span>
                            </div>
                        <?php else: ?>
                            <p class="muted" style="margin-top:8px;"><?= t('dashboard.no_role_found', 'Keine direkte Organisationsrolle gefunden.') ?></p>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <p class="muted"><?= t('dashboard.no_current_vessel', 'Kein Schiff gefunden oder zugeordnet.') ?></p>
                <?php endif; ?>
            </div>

            <div class="card card-ops">
                <h3><?= t('dashboard.active_modules', 'Aktive Module') ?></h3>
                <?php if ($modules): ?>
                    <ul class="module-list">
                        <?php foreach ($modules as $m): ?>
                            <li>
                                <strong><?= e($m['module_name']) ?></strong><br>
                                <span class="muted"><?= e($m['module_key']) ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p class="muted"><?= t('dashboard.no_modules', 'Keine Module konfiguriert.') ?></p>
                <?php endif; ?>
            </div>

            <div class="card card-ops">
                <h3><?= t('dashboard.vessel_dashboard', 'Schiffsdashboard') ?></h3>
                <?php if ($currentVessel): ?>
                    <p><?= t('dashboard.vessel_dashboard_hint', 'Öffnet das Dashboard des aktuell gewählten Schiffs.') ?></p>
                    <p><a href="/vessel_dashboard.php"><strong><?= t('dashboard.open_dashboard', 'Dashboard öffnen') ?></strong></a></p>
                    <p><a href="/v/<?= e($currentVessel['vessel_key']) ?>" target="_blank" rel="noopener noreferrer"><?= t('vessel.open_public_view', 'Öffentliche Ansicht öffnen') ?></a></p>
                <?php else: ?>
                    <p class="muted"><?= t('dashboard.no_vessel_selected', 'Kein Schiff ausgewählt.') ?></p>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <?php if ($visibleVesselAdmin || $visibleAdminUsers || $visibleOrganizationAdmin || $visibleModuleCatalog): ?>
        <section class="section-block">
            <h2 class="section-title"><?= t('dashboard.admin_title', 'Administration') ?></h2>
            <p class="section-subtitle">
                <?= t('dashboard.admin_subtitle', 'Verwaltung von Schiffsstrukturen und grundlegenden Stammdaten.') ?>
            </p>

            <div class="grid-admin-mixed">
                <?php if ($visibleVesselAdmin): ?>
                    <div class="card card-vessel-admin">
                        <h3><?= t('vessels.title', 'Schiffsverwaltung') ?></h3>
                        <p><?= t('dashboard.admin_vessels_hint', 'Schiffe, vessel_keys, Telemetry-Datenbanken und öffentliche Links verwalten.') ?></p>
                        <p><a href="/admin_vessels.php"><strong><?= t('common.open', 'Öffnen') ?></strong></a></p>
                    </div>
                <?php endif; ?>

                <?php if ($visibleAdminUsers): ?>
                    <div class="card card-masterdata">
                        <h3><?= t('users.title', 'Benutzerverwaltung') ?></h3>
                        <p><?= t('dashboard.admin_users_hint', 'Benutzer, Rollen, Sprachen und Organisationszuordnungen verwalten.') ?></p>
                        <p><a href="/admin_users.php"><strong><?= t('common.open', 'Öffnen') ?></strong></a></p>
                    </div>
                <?php endif; ?>

                <?php if ($visibleOrganizationAdmin): ?>
                    <div class="card card-masterdata">
                        <h3><?= t('organizations.title', 'Organisationsverwaltung') ?></h3>
                        <p><?= t('dashboard.admin_organizations_hint', 'Organisationen, Hierarchien, Charterbasen und Flottenstrukturen verwalten.') ?></p>
                        <p><a href="/admin_organizations.php"><strong><?= t('common.open', 'Öffnen') ?></strong></a></p>
                    </div>
                <?php endif; ?>

                <?php if ($visibleModuleCatalog): ?>
                    <div class="card card-masterdata">
                        <h3><?= t('modules.catalog_title', 'YachtMemory-Modulkatalog') ?></h3>
                        <p><?= t('dashboard.admin_modules_hint', 'Systemweite YachtMemory-Module und Kategorien verwalten.') ?></p>
                        <p><a href="/admin_modules.php"><strong><?= t('common.open', 'Öffnen') ?></strong></a></p>
                    </div>
                <?php endif; ?>
            </div>
        </section>
    <?php endif; ?>
</main>

<script>
function filterVesselList() {
    const input = document.getElementById('vesselSearch');
    const list = document.getElementById('vesselList');
    const emptyState = document.getElementById('vesselEmptyState');

    if (!input || !list || !emptyState) {
        return;
    }

    const query = input.value.trim().toLowerCase();
    const groups = list.querySelectorAll('.vessel-item-group');
    let visibleCount = 0;

    groups.forEach(function(group) {
        const vesselItems = group.querySelectorAll('.vessel-item');
        let groupHasVisibleItems = false;

        vesselItems.forEach(function(item) {
            const haystack = item.getAttribute('data-search') || '';
            const match = query === '' || haystack.includes(query);

            item.style.display = match ? '' : 'none';

            if (match) {
                groupHasVisibleItems = true;
                visibleCount++;
            }
        });

        group.style.display = groupHasVisibleItems ? '' : 'none';
    });

    emptyState.style.display = visibleCount === 0 ? 'block' : 'none';
}
</script>

</body>
</html>
