@extends('finance.layouts.app')

@section('title', 'Dashboard')

@section('content')
<div class="container-fluid">
    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-md-6">
            <h2 class="mb-1">
                <i class="bi bi-speedometer2 me-2"></i>
                Dashboard
            </h2>
            <p class="text-muted">Hoş geldiniz, {{ $user->full_name }}</p>
            <span class="badge bg-info">{{ $financeGroup->name }}</span>
        </div>
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-3">
                    <form method="GET" action="{{ route('finance.dashboard') }}" id="dateFilterForm">
                        <div class="row g-2 align-items-end">
                            <div class="col-md-4">
                                <label class="form-label small mb-1">Başlangıç Tarihi</label>
                                <input type="text" name="date_from" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm" value="{{ request()->filled('date_from') ? $dateFromDisplay->format('d/m/Y H:i') : '' }}">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label small mb-1">Bitiş Tarihi</label>
                                <input type="text" name="date_to" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm" value="{{ request()->filled('date_to') ? $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="mt-2">
                            <button type="button" class="btn btn-link btn-sm text-decoration-none p-0" onclick="setDateRange('today')">Bugün</button>
                            <span class="text-muted mx-1">|</span>
                            <button type="button" class="btn btn-link btn-sm text-decoration-none p-0" onclick="setDateRange('week')">Bu Hafta</button>
                            <span class="text-muted mx-1">|</span>
                            <button type="button" class="btn btn-link btn-sm text-decoration-none p-0" onclick="setDateRange('month')">Bu Ay</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row g-4 mb-4">
        <!-- Period Deposits -->
        <div class="col-xl-3 col-md-6">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon bg-success bg-opacity-10 text-success rounded-circle p-3 me-3">
                            <i class="bi bi-arrow-down-circle fs-4"></i>
                        </div>
                        <div class="flex-grow-1">
                            <p class="text-muted mb-1 small">Yatırımlar</p>
                            <h4 class="mb-0 text-success">
                                <span class="text-success">+</span>{{ number_format($periodDeposits, 2) }} ₺
                            </h4>
                            <small class="text-muted">{{ $periodDepositCount }} işlem</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Period Withdrawals -->
        <div class="col-xl-3 col-md-6">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon bg-danger bg-opacity-10 text-danger rounded-circle p-3 me-3">
                            <i class="bi bi-arrow-up-circle fs-4"></i>
                        </div>
                        <div class="flex-grow-1">
                            <p class="text-muted mb-1 small">Çekimler</p>
                            <h4 class="mb-0 text-danger">
                                <span class="text-danger">-</span>{{ number_format($periodWithdrawals, 2) }} ₺
                            </h4>
                            <small class="text-muted">{{ $periodWithdrawalCount }} işlem</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pending Deposits -->
        <div class="col-xl-3 col-md-6">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon bg-warning bg-opacity-10 text-warning rounded-circle p-3 me-3">
                            <i class="bi bi-hourglass-split fs-4"></i>
                        </div>
                        <div class="flex-grow-1">
                            <p class="text-muted mb-1 small">Bekleyen Yatırımlar</p>
                            <h4 class="mb-0">{{ $pendingDeposits }}</h4>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pending Withdrawals -->
        <div class="col-xl-3 col-md-6">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon bg-info bg-opacity-10 text-info rounded-circle p-3 me-3">
                            <i class="bi bi-clock-history fs-4"></i>
                        </div>
                        <div class="flex-grow-1">
                            <p class="text-muted mb-1 small">Bekleyen Çekimler</p>
                            <h4 class="mb-0">{{ $pendingWithdrawals }}</h4>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0">
                        <i class="bi bi-globe2 me-2"></i>
                        Site Bazlı Özet
                    </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 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 Farkı</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($siteStats as $siteStat)
                                    <tr>
                                        <td><strong>{{ $siteStat['name'] }}</strong></td>
                                        <td>
                                            @if($siteStat['is_active'])
                                                <span class="badge bg-success">Aktif</span>
                                            @else
                                                <span class="badge bg-secondary">Pasif</span>
                                            @endif
                                        </td>
                                        <td class="text-end">{{ $siteStat['auto_deposit_count'] }}</td>
                                        <td class="text-end">{{ $siteStat['manual_deposit_count'] }}</td>
                                        <td class="text-end text-success fw-bold">{{ number_format($siteStat['deposits'], 2) }} ₺</td>
                                        <td class="text-end text-danger fw-bold">{{ number_format($siteStat['withdrawals'], 2) }} ₺</td>
                                        <td class="text-end">
                                            @php
                                                $siteKasaClass = $siteStat['kasa_farki'] >= 0 ? 'text-success' : 'text-danger';
                                                $siteKasaSign = $siteStat['kasa_farki'] >= 0 ? '+' : '';
                                            @endphp
                                            <span class="{{ $siteKasaClass }} fw-bold">
                                                {{ $siteKasaSign }}{{ number_format($siteStat['kasa_farki'], 2) }} ₺
                                            </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>
    </div>

</div>

<style>
    .stat-card {
        transition: transform 0.2s;
    }

    .stat-card:hover {
        transform: translateY(-5px);
    }

    .stat-icon {
        width: 60px;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>


@push('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
@endpush

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

        const defaultBusinessDateFrom = @json(\App\Support\BusinessTime::startOfBusinessDay(now('Europe/Istanbul')->subDay()->format('Y-m-d'))->format('d/m/Y H:i'));
        const defaultBusinessDateTo = @json(\App\Support\BusinessTime::endOfBusinessDay(now('Europe/Istanbul')->subDay()->format('Y-m-d'))->format('d/m/Y H:i'));
        const istanbulToday = @json(now('Europe/Istanbul')->format('Y-m-d'));

        if (!$dateFrom.val() && !$dateTo.val()) {
            if (datePickers[0]) {
                datePickers[0].setDate(defaultBusinessDateFrom, true, 'd/m/Y H:i');
            }
            if (datePickers[1]) {
                datePickers[1].setDate(defaultBusinessDateTo, true, 'd/m/Y H:i');
            }
        }

        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 parts = istanbulToday.split('-');
            const baseDate = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]), 6, 0);
            let startDate = new Date(baseDate);
            if (range === 'week') {
                startDate.setDate(startDate.getDate() - 7);
            } else if (range === 'month') {
                startDate.setMonth(startDate.getMonth() - 1);
            }
            const endDate = new Date(baseDate);
            endDate.setDate(endDate.getDate() + 1);
            endDate.setHours(5, 59, 0, 0);

            if (datePickers[0]) {
                datePickers[0].setDate(startDate, true);
            }
            if (datePickers[1]) {
                datePickers[1].setDate(endDate, true);
            }
            $('#dateFilterForm').trigger('submit');
        };
    });
</script>
@endpush

@endsection
