<?php require dirname(__DIR__) . '/layouts/app.php'; ?>

<?php
$money = static fn (float $amount): string => number_format($amount, 2, ',', ' ');
$chartMax = max(1, ...array_map(static fn (array $row): float => max((float) $row['revenue'], (float) $row['expenses'], abs((float) $row['profit'])), $chartRows ?: [['revenue' => 0, 'expenses' => 0, 'profit' => 0]]));
$periodQuery = static fn (string $value): string => url('/dashboard?period=' . $value);
?>

<section class="page-heading dashboard-heading">
    <div>
        <p class="eyebrow">Dashboard</p>
        <h1>Bonjour, <?= e($user['name'] ?? 'Utilisateur') ?></h1>
        <p class="dashboard-period"><?= e($periodLabel) ?>: <?= e($from) ?> au <?= e($to) ?></p>
    </div>
    <div class="dashboard-heading-actions">
        <button class="theme-toggle" type="button" data-theme-toggle aria-label="Mode sombre" aria-pressed="false">
            <span data-theme-icon aria-hidden="true">&#9790;</span>
        </button>
        <a class="notification-bell" href="<?= url('/notifications') ?>" aria-label="Notifications">
            <span class="bell-icon" aria-hidden="true">&#128276;</span>
            <?php if (($unreadNotifications ?? 0) > 0): ?>
                <strong><?= (int) $unreadNotifications ?></strong>
            <?php endif; ?>
        </a>
        <span class="role-badge"><?= e($user['role'] ?? '') ?></span>
    </div>
</section>

<section class="dashboard-filter-panel">
    <nav class="segmented dashboard-periods" aria-label="Periode d'analyse">
        <a class="<?= $period === 'day' ? 'active' : '' ?>" href="<?= $periodQuery('day') ?>">Jour</a>
        <a class="<?= $period === 'week' ? 'active' : '' ?>" href="<?= $periodQuery('week') ?>">Semaine</a>
        <a class="<?= $period === 'month' ? 'active' : '' ?>" href="<?= $periodQuery('month') ?>">Mois</a>
        <a class="<?= $period === 'year' ? 'active' : '' ?>" href="<?= $periodQuery('year') ?>">Annee</a>
    </nav>
    <form class="dashboard-custom-period" method="get" action="<?= url('/dashboard') ?>">
        <input type="hidden" name="period" value="custom">
        <label>
            Du
            <input type="date" name="from" value="<?= e($from) ?>">
        </label>
        <label>
            Au
            <input type="date" name="to" value="<?= e($to) ?>">
        </label>
        <button type="submit">Afficher</button>
    </form>
</section>

<section class="quick-actions">
    <?php if (Auth::can('properties.create')): ?><a href="<?= url('/properties/create') ?>">Ajouter un bien</a><?php endif; ?>
    <?php if (Auth::can('reservations.create')): ?><a href="<?= url('/reservations/create') ?>">Nouvelle reservation</a><?php endif; ?>
    <?php if (Auth::can('payments.create')): ?><a href="<?= url('/payments/create') ?>">Ajouter paiement</a><?php endif; ?>
    <?php if (Auth::can('expenses.create')): ?><a href="<?= url('/expenses/create') ?>">Ajouter depense</a><?php endif; ?>
    <?php if (Auth::can('long_rentals.create')): ?><a href="<?= url('/long-rentals/contracts/create') ?>">Nouveau contrat</a><?php endif; ?>
</section>

<section class="dashboard-section">
    <div class="section-title-row">
        <div>
            <p class="eyebrow">Finances</p>
            <h2>Indicateurs prioritaires</h2>
        </div>
    </div>
    <div class="stat-grid finance-grid">
        <article class="stat-card stat-card-feature">
            <span>Montant total encaisse</span>
            <strong><?= $money((float) $stats['totalRevenue']) ?></strong>
        </article>
        <article class="stat-card">
            <span>Total des depenses</span>
            <strong><?= $money((float) $stats['expensesTotal']) ?></strong>
        </article>
        <article class="stat-card <?= $stats['netProfit'] < 0 ? 'is-negative' : 'is-positive' ?>">
            <span>Resultat net</span>
            <strong><?= $money((float) $stats['netProfit']) ?></strong>
        </article>
    </div>
</section>

<section class="dashboard-section">
    <div class="section-title-row">
        <div>
            <p class="eyebrow">Evolution</p>
            <h2>Revenus, depenses et benefice</h2>
        </div>
    </div>
    <article class="chart-panel">
        <div class="chart-legend">
            <span><i class="legend-revenue"></i>Revenus</span>
            <span><i class="legend-expenses"></i>Depenses</span>
            <span><i class="legend-profit"></i>Benefice</span>
        </div>
        <div class="trend-chart">
            <?php foreach ($chartRows as $row): ?>
                <div class="trend-group">
                    <div class="trend-bars">
                        <i class="bar-revenue" style="height: <?= max(4, ((float) $row['revenue'] / $chartMax) * 100) ?>%"></i>
                        <i class="bar-expenses" style="height: <?= max(4, ((float) $row['expenses'] / $chartMax) * 100) ?>%"></i>
                        <i class="bar-profit" style="height: <?= max(4, (abs((float) $row['profit']) / $chartMax) * 100) ?>%"></i>
                    </div>
                    <span><?= e(substr((string) $row['period_key'], 5)) ?></span>
                </div>
            <?php endforeach; ?>
            <?php if (!$chartRows): ?>
                <p class="muted">Aucune donnee financiere sur cette periode.</p>
            <?php endif; ?>
        </div>
    </article>
</section>

<section class="dashboard-section-grid">
    <article class="dashboard-category">
        <h2>Locations</h2>
        <div class="compact-stat-list">
            <div><span>Loyers encaisses</span><strong><?= $money((float) $stats['longRevenue']) ?></strong></div>
            <div><span>Locataires actifs</span><strong><?= (int) $stats['activeTenants'] ?></strong></div>
            <div><span>Loyers en attente</span><strong><?= $money((float) $stats['pendingRent']) ?></strong></div>
        </div>
    </article>

    <article class="dashboard-category">
        <h2>Reservations</h2>
        <div class="compact-stat-list">
            <div><span>Revenus courte duree</span><strong><?= $money((float) $stats['shortRevenue']) ?></strong></div>
            <div><span>Reservations</span><strong><?= (int) $stats['shortReservations'] ?></strong></div>
            <div><span>Taux occupation</span><strong><?= number_format((float) $stats['occupancyRate'], 2, ',', ' ') ?>%</strong></div>
        </div>
    </article>

    <article class="dashboard-category">
        <h2>Activite</h2>
        <div class="compact-stat-list">
            <div><span>Biens</span><strong><?= (int) $stats['properties'] ?></strong></div>
            <div><span>Clients</span><strong><?= (int) $stats['clients'] ?></strong></div>
            <div><span>Arrivees / departs</span><strong><?= (int) $stats['arrivalsToday'] ?> / <?= (int) $stats['departuresToday'] ?></strong></div>
        </div>
    </article>
</section>

<section class="stats-layout">
    <article class="table-panel">
        <h2 class="panel-title">Repartition revenus par bien</h2>
        <table>
            <thead><tr><th>Bien</th><th>Revenus</th></tr></thead>
            <tbody>
                <?php foreach ($propertyRevenueRows as $row): ?>
                    <tr><td><?= e($row['title']) ?></td><td><?= $money((float) $row['revenue']) ?></td></tr>
                <?php endforeach; ?>
                <?php if (!$propertyRevenueRows): ?><tr><td colspan="2">Aucune donnee.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </article>

    <article class="table-panel">
        <h2 class="panel-title">Dernieres reservations</h2>
        <table>
            <thead><tr><th>Bien</th><th>Client</th><th>Dates</th><th>Statut</th></tr></thead>
            <tbody>
                <?php foreach ($recentReservations as $reservation): ?>
                    <tr>
                        <td><?= e($reservation['property_title']) ?></td>
                        <td><?= e($reservation['first_name'] . ' ' . $reservation['last_name']) ?></td>
                        <td><?= e($reservation['start_date'] . ' - ' . $reservation['end_date']) ?></td>
                        <td><?= e(reservation_statuses()[$reservation['status']] ?? $reservation['status']) ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($recentReservations)): ?><tr><td colspan="4">Aucune reservation pour le moment.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </article>
</section>

<?php require dirname(__DIR__) . '/layouts/app_footer.php'; ?>
