@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;
    }

    .dash-site-block {
        border: 1px solid #e5e7eb;
        border-radius: 14px;
        overflow: hidden;
        background: #fff;
    }

    .dash-site-block + .dash-site-block {
        margin-top: 1.6rem;
    }

    .dash-site-block-header {
        position: relative;
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 1rem;
        padding: 0.95rem 1.1rem;
        background: linear-gradient(180deg, #fbfdff 0%, #f8fafc 100%);
        border-bottom: 1px solid #e5e7eb;
    }

    .dash-site-block-title {
        font-size: 1.6rem;
        font-weight: 700;
        color: #1f2937;
        margin: 0;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        text-align: center;
    }

    .dash-site-block-meta {
        display: flex;
        align-items: center;
        gap: 0.6rem;
        flex-wrap: wrap;
        justify-content: flex-end;
    }

    .dash-site-block-table .table th,
    .dash-site-block-table .table td {
        white-space: nowrap;
    }

    .dash-site-block-table .table {
        table-layout: auto;
        width: 100%;
    }

    .dash-col-group {
        width: 18%;
    }

    .dash-col-count {
        width: 14%;
    }

    .dash-col-amount {
        width: 18%;
    }

    .dash-total-row > td {
        background: #f8fafc !important;
        font-weight: 700;
    }

    /* Mobile responsiveness fixes */
    .dash-table-card .table-responsive,
    .dash-site-block-table {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    .dash-table-card .table,
    .dash-site-block-table .table {
        min-width: 760px;
    }

    .dash-site-block-title,
    .dash-section-title,
    .dash-kpi-value {
        overflow-wrap: anywhere;
        word-break: normal;
    }

    .dash-site-block-title {
        position: static;
        transform: none;
        left: auto;
        flex: 1 1 auto;
        min-width: 0;
        text-align: left;
    }

    .dash-site-block-meta {
        flex: 0 0 auto;
    }

    @media (max-width: 767.98px) {
        .container-fluid {
            padding-left: 0.75rem;
            padding-right: 0.75rem;
        }

        .dash-header-title {
            font-size: 1.45rem;
        }

        .dash-section-title {
            font-size: 1.15rem;
            line-height: 1.25;
        }

        .dash-kpi-card .card-body,
        .dash-header-card .card-body,
        .dash-table-card .card-body {
            padding: 0.85rem;
        }

        .dash-kpi-value {
            font-size: 1.35rem;
        }

        .dash-kpi-label {
            font-size: 0.82rem;
        }

        .dash-kpi-icon {
            width: 42px;
            height: 42px;
        }

        .dash-site-block-header {
            align-items: flex-start;
            flex-direction: column;
            gap: 0.5rem;
            padding: 0.8rem;
        }

        .dash-site-block-title {
            font-size: 1.15rem;
            line-height: 1.25;
            width: 100%;
        }

        .dash-site-block-meta {
            width: 100%;
            justify-content: flex-start;
        }

        .dash-table-card .card-header {
            padding: 0.8rem;
        }

        .dash-table-card .table th,
        .dash-table-card .table td {
            font-size: 0.82rem;
        }
    }

    @media (max-width: 575.98px) {
        .dash-table-card .table,
        .dash-site-block-table .table {
            min-width: 700px;
        }

        .dash-col-group { width: 20%; }
        .dash-col-count { width: 13%; }
        .dash-col-amount { width: 18%; }
    }

</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')">Dün</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-4 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">Yatırımlar</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-4 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">Çekimler</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-2 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 Yatırım Islem Sayisi</p>
                            <p class="dash-kpi-value">{{ $autoDepositCount }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-2 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 Yatırım 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 Finans Ozetleri
            </h5>
        </div>
        <div class="card-body">
            @forelse($sites as $site)
                @php
                    $siteSummary = $siteStatsById->get($site->id, [
                        'auto_deposit_count' => 0,
                        'manual_deposit_count' => 0,
                        'deposits' => 0,
                        'withdrawals' => 0,
                        'kasa_farki' => 0,
                    ]);
                @endphp
                <div class="dash-site-block">
                    <div class="dash-site-block-header">
                        <h6 class="dash-site-block-title">{{ $site->name }}</h6>
                        <div class="dash-site-block-meta">
                            @if($site->is_active)
                                <span class="badge bg-success">Aktif</span>
                            @else
                                <span class="badge bg-secondary">Pasif</span>
                            @endif
                            <span class="badge bg-light text-dark border">Genel Site Toplami</span>
                        </div>
                    </div>
                    <div class="table-responsive dash-site-block-table">
                        <table class="table table-hover mb-0">
                            <colgroup>
                                <col class="dash-col-group">
                                <col class="dash-col-count">
                                <col class="dash-col-count">
                                <col class="dash-col-amount">
                                <col class="dash-col-amount">
                                <col class="dash-col-amount">
                            </colgroup>
                            <thead class="table-light">
                                <tr>
                                    <th>Finans Grubu</th>
                                    <th class="text-end">Auto Yatırım</th>
                                    <th class="text-end">Manuel Yatırım</th>
                                    <th class="text-end">Yatırım Tutar</th>
                                    <th class="text-end">Çekim Tutar</th>
                                    <th class="text-end">Kasa Farki</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($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);
                                        $siteGroup = $siteFinanceStats[$site->id][$groupId] ?? [
                                            'auto_deposit_count' => 0,
                                            'manual_deposit_count' => 0,
                                            'deposits' => 0,
                                            'withdrawals' => 0,
                                            'kasa_farki' => 0,
                                        ];
                                        $siteGroupKasaClass = $siteGroup['kasa_farki'] >= 0 ? 'text-success' : 'text-danger';
                                        $siteGroupKasaSign = $siteGroup['kasa_farki'] >= 0 ? '+' : '';
                                    @endphp
                                    <tr>
                                        <td><strong>{{ $groupName }}</strong></td>
                                        <td class="text-end">{{ (int) data_get($siteGroup, 'auto_deposit_count', 0) }}</td>
                                        <td class="text-end">{{ (int) data_get($siteGroup, 'manual_deposit_count', 0) }}</td>
                                        <td class="text-end text-success fw-bold">{{ number_format((float) data_get($siteGroup, 'deposits', 0), 2) }} &#8378;</td>
                                        <td class="text-end text-danger fw-bold">{{ number_format((float) data_get($siteGroup, 'withdrawals', 0), 2) }} &#8378;</td>
                                        <td class="text-end">
                                            <span class="{{ $siteGroupKasaClass }} fw-bold">
                                                {{ $siteGroupKasaSign }}{{ number_format((float) data_get($siteGroup, 'kasa_farki', 0), 2) }} &#8378;
                                            </span>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                            <tfoot>
                                @php
                                    $siteTotalKasaFarki = (float) data_get($siteSummary, 'kasa_farki', 0);
                                    $siteTotalKasaClass = $siteTotalKasaFarki >= 0 ? 'text-success' : 'text-danger';
                                    $siteTotalKasaSign = $siteTotalKasaFarki >= 0 ? '+' : '';
                                @endphp
                                <tr class="dash-total-row">
                                    <td>TOPLAM</td>
                                    <td class="text-end">{{ (int) data_get($siteSummary, 'auto_deposit_count', 0) }}</td>
                                    <td class="text-end">{{ (int) data_get($siteSummary, 'manual_deposit_count', 0) }}</td>
                                    <td class="text-end text-success fw-bold">{{ number_format((float) data_get($siteSummary, 'deposits', 0), 2) }} &#8378;</td>
                                    <td class="text-end text-danger fw-bold">{{ number_format((float) data_get($siteSummary, 'withdrawals', 0), 2) }} &#8378;</td>
                                    <td class="text-end">
                                        <span class="{{ $siteTotalKasaClass }} fw-bold">
                                            {{ $siteTotalKasaSign }}{{ number_format($siteTotalKasaFarki, 2) }} &#8378;
                                        </span>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            @empty
                <div class="text-center py-4 text-muted">Site bulunmuyor.</div>
            @endforelse
        </div>
    </div>

    <div class="card dash-table-card">
        <div class="card-header">
            <h5 class="dash-section-title">
                <i class="bi bi-diagram-3"></i> Genel 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>Finans Grubu</th>
                            <th class="text-end">Auto Yatırım</th>
                            <th class="text-end">Manuel Yatırım</th>
                            <th class="text-end">Yatırım Tutar</th>
                            <th class="text-end">Çekim Tutar</th>
                            <th class="text-end">Kasa Farki</th>
                        </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 class="text-end">{{ $group['auto_deposit_count'] ?? 0 }}</td>
                                <td class="text-end">{{ $group['manual_deposit_count'] ?? 0 }}</td>
                                <td class="text-end">
                                    <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>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" class="text-center py-4 text-muted">
                                    Finans grubu bulunmuyor.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                    <tfoot>
                        <tr class="dash-total-row">
                            <td>TOPLAM</td>
                            <td class="text-end">{{ $autoDepositCount }}</td>
                            <td class="text-end">{{ $manualDepositCount }}</td>
                            <td class="text-end">
                                <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>
                        </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
