@extends('backoffice.layouts.app')

@section('title', 'Dashboard')

@push('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
    .dash-header-card,
    .dash-kpi-card,
    .dash-table-card,
    .dash-site-mini-card {
        border: 0;
        border-radius: 12px;
        box-shadow: 0 0.125rem 0.55rem rgba(0, 0, 0, 0.06);
    }

    .dash-header-card .card-body,
    .dash-kpi-card .card-body,
    .dash-site-mini-card .card-body {
        padding: 1rem 1.1rem;
    }

    .dash-header-title {
        font-size: 2rem;
        font-weight: 700;
        color: #1f2937;
        margin-bottom: 0.2rem;
    }

    .dash-kpi-card {
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .dash-kpi-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 0.4rem 1.2rem rgba(0, 0, 0, 0.1);
    }

    .dash-kpi-icon {
        width: 48px;
        height: 48px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 999px;
        font-size: 1.15rem;
        flex-shrink: 0;
    }

    .dash-kpi-label {
        font-size: 0.9rem;
        color: #6b7280;
        margin-bottom: 0.15rem;
    }

    .dash-kpi-value {
        font-size: 1.9rem;
        line-height: 1.1;
        font-weight: 700;
        margin-bottom: 0;
    }

    .dash-quick-range {
        font-size: 0.85rem;
    }

    .dash-quick-range button {
        border: 0;
        background: transparent;
        color: #0d6efd;
        padding: 0;
    }

    .dash-quick-range button:hover {
        text-decoration: underline;
    }

    .dash-section-title {
        display: flex;
        align-items: center;
        gap: 0.45rem;
        margin: 0;
        font-size: 1.3rem;
        font-weight: 700;
        color: #1f2937;
    }

    .dash-table-card .card-header {
        border-bottom: 1px solid #e5e7eb;
        border-top-left-radius: 12px;
        border-top-right-radius: 12px;
        background: #fff;
        padding: 0.9rem 1.1rem;
    }

    .dash-table-card .table th {
        font-size: 0.86rem;
        color: #374151;
        font-weight: 700;
    }

    .dash-table-card .table td {
        vertical-align: middle;
        font-size: 0.92rem;
    }

    .finance-group-highlight-row > td {
        background: var(--group-row-highlight, transparent) !important;
    }

    .table-hover .finance-group-highlight-row:hover > td {
        filter: brightness(0.98);
    }

    .dash-table-card .table tfoot td {
        background: #f8fafc;
    }

    .dash-site-mini-card h6 {
        font-size: 1.05rem;
        margin: 0;
        font-weight: 700;
    }

    .dash-mini-metric {
        font-size: 0.87rem;
        color: #6b7280;
        margin-bottom: 0.2rem;
    }

    .dash-mini-value {
        font-size: 1.02rem;
        font-weight: 700;
    }
</style>
@endpush

@section('content')
@php
    $sites = $sites ?? collect();
    $siteStats = $siteStats ?? collect();
    $financeGroups = $financeGroups ?? collect();
    $siteFinanceStats = is_array($siteFinanceStats ?? null) ? $siteFinanceStats : [];
    $siteStatsById = $siteStatsById ?? collect();
    if (!($siteStatsById instanceof \Illuminate\Support\Collection)) {
        $siteStatsById = collect($siteStatsById);
    }
@endphp
<div class="container-fluid">
    <div class="row g-3 align-items-stretch mb-4">
        <div class="col-lg-5">
            <div class="card dash-header-card h-100">
                <div class="card-body d-flex flex-column justify-content-center">
                    <h2 class="dash-header-title">
                        <i class="bi bi-speedometer2 me-1"></i> Dashboard
                    </h2>
                    <p class="text-muted mb-0">Hos geldiniz, {{ optional($user)->full_name ?? '-' }}</p>
                </div>
            </div>
        </div>
        <div class="col-lg-7">
            <div class="card dash-header-card h-100">
                <div class="card-body">
                    <form method="GET" action="{{ route('backoffice.dashboard') }}" id="dateFilterForm">
                        <div class="row g-2 align-items-end">
                            <div class="col-md-4">
                                <label class="form-label small mb-1">Baslangic Tarihi</label>
                                <input type="text" name="date_from" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm" value="{{ $dateFromDisplay->format('d/m/Y H:i') }}">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label small mb-1">Bitis Tarihi</label>
                                <input type="text" name="date_to" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm" value="{{ $dateToDisplay->format('d/m/Y H:i') }}">
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary btn-sm w-100">
                                    <i class="bi bi-funnel me-1"></i> Filtrele
                                </button>
                            </div>
                        </div>
                        <div class="dash-quick-range mt-2">
                            <button type="button" onclick="setDateRange('yesterday')">Dun</button>
                            <span class="text-muted mx-1">|</span>
                            <button type="button" onclick="setDateRange('today')">Bugun</button>
                            <span class="text-muted mx-1">|</span>
                            <button type="button" onclick="setDateRange('week')">Bu Hafta</button>
                            <span class="text-muted mx-1">|</span>
                            <button type="button" onclick="setDateRange('month')">Bu Ay</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-xl-3 col-md-6">
            <div class="card dash-kpi-card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center gap-3">
                        <span class="dash-kpi-icon text-success bg-success-subtle">
                            <i class="bi bi-arrow-down-circle"></i>
                        </span>
                        <div class="w-100">
                            <p class="dash-kpi-label">Yatirimlar</p>
                            <p class="dash-kpi-value text-success">{{ number_format($periodDeposits, 2) }} &#8378;</p>
                            <small class="text-muted">{{ $periodDepositCount }} islem</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="card dash-kpi-card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center gap-3">
                        <span class="dash-kpi-icon text-danger bg-danger-subtle">
                            <i class="bi bi-arrow-up-circle"></i>
                        </span>
                        <div class="w-100">
                            <p class="dash-kpi-label">Cekimler</p>
                            <p class="dash-kpi-value text-danger">{{ number_format($periodWithdrawals, 2) }} &#8378;</p>
                            <small class="text-muted">{{ $periodWithdrawalCount }} islem</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="card dash-kpi-card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center gap-3">
                        <span class="dash-kpi-icon text-warning bg-warning-subtle">
                            <i class="bi bi-hourglass-split"></i>
                        </span>
                        <div class="w-100">
                            <p class="dash-kpi-label">Auto Yatirim Islem Sayisi</p>
                            <p class="dash-kpi-value">{{ $autoDepositCount }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="card dash-kpi-card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center gap-3">
                        <span class="dash-kpi-icon text-primary bg-primary-subtle">
                            <i class="bi bi-diagram-3"></i>
                        </span>
                        <div class="w-100">
                            <p class="dash-kpi-label">Manuel Yatirim Islem Sayisi</p>
                            <p class="dash-kpi-value">{{ $manualDepositCount }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card dash-table-card mb-4">
        <div class="card-header">
            <h5 class="dash-section-title">
                <i class="bi bi-globe2"></i> Site Bazli Ozet
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Site</th>
                            <th>Durum</th>
                            <th class="text-end">Auto Yatirim</th>
                            <th class="text-end">Manuel Yatirim</th>
                            <th class="text-end">Yatirim Tutar</th>
                            <th class="text-end">Cekim Tutar</th>
                            <th class="text-end">Kasa Farki</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($siteStats as $siteStat)
                            @php
                                $siteName = (string) data_get($siteStat, 'name', '-');
                                $siteIsActive = (bool) data_get($siteStat, 'is_active', false);
                                $siteAutoDepositCount = (int) data_get($siteStat, 'auto_deposit_count', 0);
                                $siteManualDepositCount = (int) data_get($siteStat, 'manual_deposit_count', 0);
                                $siteDeposits = (float) data_get($siteStat, 'deposits', 0);
                                $siteWithdrawals = (float) data_get($siteStat, 'withdrawals', 0);
                                $siteKasaFarki = (float) data_get($siteStat, 'kasa_farki', 0);
                            @endphp
                            <tr>
                                <td><strong>{{ $siteName }}</strong></td>
                                <td>
                                    @if($siteIsActive)
                                        <span class="badge bg-success">Aktif</span>
                                    @else
                                        <span class="badge bg-secondary">Pasif</span>
                                    @endif
                                </td>
                                <td class="text-end">{{ $siteAutoDepositCount }}</td>
                                <td class="text-end">{{ $siteManualDepositCount }}</td>
                                <td class="text-end text-success fw-bold">{{ number_format($siteDeposits, 2) }} &#8378;</td>
                                <td class="text-end text-danger fw-bold">{{ number_format($siteWithdrawals, 2) }} &#8378;</td>
                                <td class="text-end">
                                    @php
                                        $siteKasaClass = $siteKasaFarki >= 0 ? 'text-success' : 'text-danger';
                                        $siteKasaSign = $siteKasaFarki >= 0 ? '+' : '';
                                    @endphp
                                    <span class="{{ $siteKasaClass }} fw-bold">
                                        {{ $siteKasaSign }}{{ number_format($siteKasaFarki, 2) }} &#8378;
                                    </span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="7" class="text-center py-4 text-muted">Site bulunmuyor.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="card dash-table-card">
        <div class="card-header">
            <h5 class="dash-section-title">
                <i class="bi bi-diagram-3"></i> Finans Gruplari Ozeti
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th rowspan="2">Finans Grubu</th>
                            <th rowspan="2">Durum</th>
                            <th colspan="3" class="text-center border-start">Genel</th>
                            @foreach($sites as $site)
                                <th colspan="3" class="text-center border-start">{{ $site->name }}</th>
                            @endforeach
                        </tr>
                        <tr>
                            <th class="text-end border-start">Yatirimlar</th>
                            <th class="text-end">Cekimler</th>
                            <th class="text-end">Kasa Farki</th>
                            @foreach($sites as $site)
                                <th class="text-end border-start">Yatirimlar</th>
                                <th class="text-end">Cekimler</th>
                                <th class="text-end">Kasa Farki</th>
                            @endforeach
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($financeGroups as $group)
                            @php
                                $groupId = (int) data_get($group, 'id', 0);
                                $groupName = (string) data_get($group, 'name', '-');
                                $groupIsActive = (bool) data_get($group, 'is_active', false);
                                $groupDeposits = (float) data_get($group, 'deposits', 0);
                                $groupWithdrawals = (float) data_get($group, 'withdrawals', 0);
                                $groupDepositCount = (int) data_get($group, 'deposit_count', 0);
                                $groupWithdrawalCount = (int) data_get($group, 'withdrawal_count', 0);
                                $groupKasaFarki = (float) data_get($group, 'kasa_farki', 0);
                                $groupColor = trim((string) data_get($group, 'badge_color', ''));
                                $normalizedColor = ltrim($groupColor, '#');
                                if (preg_match('/^[0-9a-fA-F]{3}$/', $normalizedColor)) {
                                    $normalizedColor = $normalizedColor[0] . $normalizedColor[0]
                                        . $normalizedColor[1] . $normalizedColor[1]
                                        . $normalizedColor[2] . $normalizedColor[2];
                                }
                                $rowHighlight = preg_match('/^[0-9a-fA-F]{6}$/', $normalizedColor)
                                    ? ('#' . $normalizedColor . '14')
                                    : 'transparent';
                            @endphp
                            <tr class="finance-group-highlight-row" style="--group-row-highlight: {{ $rowHighlight }};">
                                <td><strong>{{ $groupName }}</strong></td>
                                <td>
                                    @if($groupIsActive)
                                        <span class="badge bg-success">Aktif</span>
                                    @else
                                        <span class="badge bg-secondary">Pasif</span>
                                    @endif
                                </td>
                                <td class="text-end border-start">
                                    <span class="text-success fw-bold">{{ number_format($groupDeposits, 2) }} &#8378;</span><br>
                                    <small class="text-muted">{{ $groupDepositCount }} islem</small>
                                </td>
                                <td class="text-end">
                                    <span class="text-danger fw-bold">{{ number_format($groupWithdrawals, 2) }} &#8378;</span><br>
                                    <small class="text-muted">{{ $groupWithdrawalCount }} islem</small>
                                </td>
                                <td class="text-end">
                                    @php
                                        $groupKasaClass = $groupKasaFarki >= 0 ? 'text-success' : 'text-danger';
                                        $groupKasaSign = $groupKasaFarki >= 0 ? '+' : '';
                                    @endphp
                                    <span class="{{ $groupKasaClass }} fw-bold">
                                        {{ $groupKasaSign }}{{ number_format($groupKasaFarki, 2) }} &#8378;
                                    </span>
                                </td>
                                @foreach($sites as $site)
                                    @php
                                        $siteGroup = $siteFinanceStats[$site->id][$groupId] ?? [
                                            'deposits' => 0,
                                            'withdrawals' => 0,
                                            'deposit_count' => 0,
                                            'withdrawal_count' => 0,
                                            'kasa_farki' => 0,
                                        ];
                                        $siteGroupKasaClass = $siteGroup['kasa_farki'] >= 0 ? 'text-success' : 'text-danger';
                                        $siteGroupKasaSign = $siteGroup['kasa_farki'] >= 0 ? '+' : '';
                                    @endphp
                                    <td class="text-end border-start">
                                        <span class="text-success fw-bold">{{ number_format($siteGroup['deposits'], 2) }} &#8378;</span><br>
                                        <small class="text-muted">{{ $siteGroup['deposit_count'] }} islem</small>
                                    </td>
                                    <td class="text-end">
                                        <span class="text-danger fw-bold">{{ number_format($siteGroup['withdrawals'], 2) }} &#8378;</span><br>
                                        <small class="text-muted">{{ $siteGroup['withdrawal_count'] }} islem</small>
                                    </td>
                                    <td class="text-end">
                                        <span class="{{ $siteGroupKasaClass }} fw-bold">
                                            {{ $siteGroupKasaSign }}{{ number_format($siteGroup['kasa_farki'], 2) }} &#8378;
                                        </span>
                                    </td>
                                @endforeach
                            </tr>
                        @empty
                            <tr>
                                <td colspan="{{ 5 + (count($sites) * 3) }}" class="text-center py-4 text-muted">
                                    Finans grubu bulunmuyor.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="2" class="fw-bold">TOPLAM</td>
                            <td class="text-end border-start">
                                <span class="text-success fw-bold">{{ number_format($periodDeposits, 2) }} &#8378;</span><br>
                                <small class="text-muted">{{ $periodDepositCount }} islem</small>
                            </td>
                            <td class="text-end">
                                <span class="text-danger fw-bold">{{ number_format($periodWithdrawals, 2) }} &#8378;</span><br>
                                <small class="text-muted">{{ $periodWithdrawalCount }} islem</small>
                            </td>
                            <td class="text-end">
                                @php
                                    $totalKasaFarki = $periodDeposits - $periodWithdrawals;
                                    $totalKasaClass = $totalKasaFarki >= 0 ? 'text-success' : 'text-danger';
                                    $totalKasaSign = $totalKasaFarki >= 0 ? '+' : '';
                                @endphp
                                <span class="{{ $totalKasaClass }} fw-bold">{{ $totalKasaSign }}{{ number_format($totalKasaFarki, 2) }} &#8378;</span>
                            </td>
                            @foreach($sites as $site)
                                @php
                                    $siteTotal = $siteStatsById->get($site->id, [
                                        'deposits' => 0,
                                        'withdrawals' => 0,
                                        'deposit_count' => 0,
                                        'withdrawal_count' => 0,
                                        'kasa_farki' => 0,
                                    ]);
                                    $siteTotalDeposits = (float) data_get($siteTotal, 'deposits', 0);
                                    $siteTotalWithdrawals = (float) data_get($siteTotal, 'withdrawals', 0);
                                    $siteTotalDepositCount = (int) data_get($siteTotal, 'deposit_count', 0);
                                    $siteTotalWithdrawalCount = (int) data_get($siteTotal, 'withdrawal_count', 0);
                                    $siteTotalKasaFarki = (float) data_get($siteTotal, 'kasa_farki', 0);
                                    $siteTotalKasaClass = $siteTotalKasaFarki >= 0 ? 'text-success' : 'text-danger';
                                    $siteTotalKasaSign = $siteTotalKasaFarki >= 0 ? '+' : '';
                                @endphp
                                <td class="text-end border-start">
                                    <span class="text-success fw-bold">{{ number_format($siteTotalDeposits, 2) }} &#8378;</span><br>
                                    <small class="text-muted">{{ $siteTotalDepositCount }} islem</small>
                                </td>
                                <td class="text-end">
                                    <span class="text-danger fw-bold">{{ number_format($siteTotalWithdrawals, 2) }} &#8378;</span><br>
                                    <small class="text-muted">{{ $siteTotalWithdrawalCount }} islem</small>
                                </td>
                                <td class="text-end">
                                    <span class="{{ $siteTotalKasaClass }} fw-bold">
                                        {{ $siteTotalKasaSign }}{{ number_format($siteTotalKasaFarki, 2) }} &#8378;
                                    </span>
                                </td>
                            @endforeach
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
    $(document).ready(function() {
        const $dateFrom = $('input[name="date_from"]');
        const $dateTo = $('input[name="date_to"]');

        const datePickers = flatpickr('.datetimepicker', {
            enableTime: true,
            time_24hr: true,
            dateFormat: 'd/m/Y H:i',
            minuteIncrement: 1,
            allowInput: true
        });

        function toIsoDateTime(value) {
            if (!value) return '';
            const [datePart, timePart] = value.split(' ');
            const parts = datePart.split('/');
            if (parts.length !== 3) return value;
            const time = timePart || '00:00';
            return `${parts[2]}-${parts[1]}-${parts[0]} ${time}`;
        }

        $('#dateFilterForm').on('submit', function() {
            $dateFrom.val(toIsoDateTime($dateFrom.val()));
            $dateTo.val(toIsoDateTime($dateTo.val()));
        });

        window.setDateRange = function(range) {
            const now = new Date();
            let startDate = new Date(now);
            let endDate = new Date(now);

            if (range === 'today') {
                startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 6, 0, 0, 0);
                if (now.getHours() < 6) {
                    startDate.setDate(startDate.getDate() - 1);
                }
            } else if (range === 'yesterday') {
                const businessStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 6, 0, 0, 0);
                if (now.getHours() < 6) {
                    businessStart.setDate(businessStart.getDate() - 1);
                }
                endDate = new Date(businessStart);
                endDate.setMilliseconds(endDate.getMilliseconds() - 1);
                startDate = new Date(businessStart);
                startDate.setDate(startDate.getDate() - 1);
            } else if (range === 'week') {
                startDate.setDate(now.getDate() - 7);
                startDate.setHours(6, 0, 0, 0);
            } else if (range === 'month') {
                startDate.setMonth(now.getMonth() - 1);
                startDate.setHours(6, 0, 0, 0);
            }

            if (datePickers[0]) {
                datePickers[0].setDate(startDate, true);
            }
            if (datePickers[1]) {
                datePickers[1].setDate(endDate, true);
            }

            $('#dateFilterForm').trigger('submit');
        };
    });
</script>
@endpush
