@php $title = __('Plans Report'); @endphp

@extends('layouts.master', [
    'title' => $title
])

@section('content')
    <x-page-header
        :title="$title"
        :breadcrumbs="[
            ['name' => __('Home'), 'url' => route('dashboard.index')]
        ]"
    />

    <form id="form-customers" method="POST" action="{{ route('reports.plans.filter') }}" enctype="multipart/form-data">
        @csrf
        <x-card class="card-2" cardLabel="fs-5">
            <x-slot:label>{{ __('Report Filters') }}</x-slot:label>

            <x-row>
                <x-col size="3">
                    <x-form-label :label="__('User')" for="user_id"></x-form-label>
                    <x-form-select name="user_id" id="user_id" class="users-select" />
                </x-col>
                <x-col size="3">
                    <x-form-label :label="__('Type')" for="type" :required="true" />
                    <x-form-select name="type" id="type"
                                   :options="config('data-select.plans-types')" :valueName="LOCALIZE_NAME" selected="{{ $request['type'] ?? '' }}"
                    />
                </x-col>
{{--                <x-col size="3">--}}
{{--                    <x-form-label :label="__('Plan')" for="plan_id"/>--}}
{{--                    <x-form-select name="plan_id" id="plan_id" class="plans-select" />--}}
{{--                </x-col>--}}
                <x-col size="3">
                    <x-form-label :label="__('From Date')" for="from_date" />
                    <x-form-input type="text" name="from_date" class="flatpickr_date" id="from_date" :value="$request['from_date'] ?? ''" />
                </x-col>
                <x-col size="3">
                    <x-form-label :label="__('To Date')" for="to_date" />
                    <x-form-input type="text" name="to_date" class="flatpickr_date" id="to_date" :value="$request['to_date'] ?? ''" />
                </x-col>
            </x-row>

            <x-row class="text-end">
                <x-col size="12">
                    <x-button type="submit" size="sm" class="btn-primary">{{ __('Save Data') }}</x-button>
                </x-col>
            </x-row>
        </x-card>
    </form>

    @if(isset($statistics))
        @php
            $cards = [
                [
                    'title' => __('Total Plans'),
                    'value' => $statistics['total_plans'],
                    'icon'  => 'bx-layer',
                    'color' => 'info'
                ],
                [
                    'title' => __('Active Plans'),
                    'value' => $statistics['active_plans'],
                    'icon'  => 'bx-check-circle',
                    'color' => 'success'
                ],
                [
                    'title' => __('Total Contributions'),
                    'value' => $statistics['total_subscriptions'],
                    'icon'  => 'bx-group',
                    'color' => 'primary'
                ],
                [
                    'title' => __('Total Revenue'),
                    'value' => getPriceFormat($statistics['total_revenue']),
                    'icon'  => 'bx-dollar-circle',
                    'color' => 'warning'
                ],
            ];
        @endphp

        <x-row>
            @foreach($cards as $card)
                <x-col size="6" class="col-xl-3">
                    <div class="card mini-stats-wid shadow-sm border-0">
                        <div class="card-body d-flex align-items-center">

                            <div @class('flex-grow-1')>
                                <p class="text-muted fw-medium mb-1">
                                    {{ $card['title'] }}
                                </p>

                                <h4 class="mb-0 fw-bold">
                                    {{ $card['value'] }}
                                </h4>
                            </div>

                            <div @class('flex-shrink-0')>
                                <div class="avatar-sm rounded-circle bg-{{ $card['color'] }} d-flex align-items-center justify-content-center">
                                    <i class="bx {{ $card['icon'] }} font-size-24 text-white"></i>
                                </div>
                            </div>

                        </div>
                    </div>
                </x-col>
            @endforeach
        </x-row>
    @endif

    @if(!empty($typeDistribution))

        @php
            $planTypes = config('data-select.plans-types');
        @endphp

        <x-card class="card-2" cardLabel="fs-5">
            <x-slot:label>{{ __('Distribution of plans by type') }}</x-slot:label>

            <x-row>
                @foreach($typeDistribution as $type)
                    @php
                        $typeName = getLocalizedName($planTypes[$type['type']] ?? $type['type']);
                    @endphp

                    <x-col size="6" class="col-xl-3">
                        <div class="mini-stats-wid bg-light border rounded p-4 h-100">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <span class="fw-semibold text-dark">{{ $typeName }}</span>
                                <span class="badge bg-primary">{{ $type['count'] }} {{ __('plan') }}</span>
                            </div>

                            <div class="row">
                                <div class="col-6">
                                    <p class="text-muted small mb-1">{{ __('Subscriptions') }}</p>
                                    <p class="fs-5 fw-bold mb-0">
                                        {{ $type['subscriptions'] }}
                                    </p>
                                </div>
                                <div class="col-6">
                                    <p class="text-muted small mb-1">{{ __('Revenue') }}</p>
                                    <p class="fs-5 fw-bold text-primary mb-0">
                                        {{ getPriceFormat($type['revenue']) }}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </x-col>
                @endforeach
            </x-row>
        </x-card>
    @endif

    @if(isset($topPlans) && $topPlans->count() > 0)
    <x-card class="card-2" cardLabel="fs-5">
        <x-slot:label>{{ __('All Plans Overview') }}</x-slot:label>

        <x-data-table
            id="best-performing-plans-table"
            :checkbox="false"
            :columns="[
                ['label' => 'ID', 'width' => '40px'],
                ['label' => __('Plan and subscriptions')],
                ['label' => __('Revenue')],
            ]"
        >
            @foreach($topPlans as $index => $plan)
                <tr>
                    @php
                        $badgeClass = match($index) {
                            0 => 'bg-warning text-dark',
                            1 => 'bg-secondary text-white',
                            2 => 'bg-dark text-white',
                            default => 'bg-primary text-white',
                        };
                    @endphp
                    <td>
                        <div class="d-flex align-items-center justify-content-center rounded-circle me-3 {{ $badgeClass }}" style="width:32px; height:32px;" >
                            {{ $index + 1 }}
                        </div>
                    </td>
                    <td>
                        <a class="fw-semibold text-dark text-decoration-none">
                            {{ $plan->name }}
                        </a>
                        <p class="text-muted small mb-0">{{ $plan->subscriptions_count }} {{ __('اشتراك') }}</p>
                    </td>
                    <td>
                        <p class="fw-bold text-primary mb-0">{{ getPriceFormat($plan->subscriptions->sum('total_revenue')) }}</p>
                    </td>
                </tr>
            @endforeach
        </x-data-table>
    </x-card>
    @endif

    @if(isset($plans) && $plans->count() > 0)
    <x-card class="card-2" cardLabel="fs-5">
        <x-slot:label>{{ __('Monthly Revenue Analysis') }}</x-slot:label>

        <x-data-table
            id="plans-table"
            :checkbox="false"
            :columns="[
                ['label' => 'ID', 'width' => '40px'],
                ['label' => __('Plan')],
                ['label' => __('Type')],
                ['label' => __('Price')],
                ['label' => __('Subscriptions Count')],
                ['label' => __('Revenue')],
                ['label' => __('Status')],
//                ['label' => __('Actions')],
            ]"
        >
            @forelse($plans as $plan)
                <tr class="align-middle">
                    <td>{{ $plan->id }}</td>
                    <td>{{ $plan->name }}</td>
                    <td>{{ getLocalizedName(config('data-select.plans-types')[$plan->type]) }}</td>
                    <td>{{ getPriceFormat($plan->price) }}</td>
                    <td>
                        <span class="fw-semibold text-primary">{{ $plan->subscriptions_count }}</span>
                    </td>
                    <td>
                        <span class="fw-semibold text-success">
                            {{ getPriceFormat($plan->subscriptions->sum('total_revenue')) }}
                        </span>
                    </td>
                    <td>{!! badgeStatus($plan->is_active) !!}</td>
{{--                    <td>--}}
{{--                        <a href="{{ route('reports.plans.details', $plan->id) }}" class="text-primary" title="{{ __('View details') }}">--}}
{{--                            <i class="bx bx-show fs-5"></i>--}}
{{--                        </a>--}}
{{--                    </td>--}}
                </tr>
            @empty
                <tr>
                    <td colspan="6" class="text-center py-5">
                        <i class="bx bx-data fs-1 text-muted"></i>
                        <p class="mt-3 text-muted">{{ __('No plans available') }}</p>
                    </td>
                </tr>
            @endforelse
        </x-data-table>
    </x-card>
    @endif

    @if(isset($monthlyRevenue))
        <x-card class="card-2" cardLabel="fs-5">
            <x-slot:label>{{ __('Monthly Revenue Overview') }}</x-slot:label>

            <div class="d-grid gap-3">
            @foreach($monthlyRevenue as $month)
                @php
                    $maxRevenue = $monthlyRevenue->max('revenue');
                    $percentage = monthlyRevenueLabel($month, $monthlyRevenue->max('revenue'))['percentage'];
                    $monthName = monthlyRevenueLabel($month, $monthlyRevenue->max('revenue'))['label'];
                @endphp

                <div class="d-flex align-items-center">
                    <div style="width: 120px;">
                        <span class="text-muted fw-medium small">{{ $monthName }}</span>
                    </div>

                    <div @class("flex-grow-1 mx-3")>
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar bg-primary" role="progressbar"
                                 style="width: {{ $percentage }}%;"
                                 aria-valuenow="{{ $percentage }}" aria-valuemin="0" aria-valuemax="100">
                            </div>
                        </div>
                    </div>

                    <div class="text-end" style="width: 150px;">
                        <span class="fw-semibold text-primary">{{ getPriceFormat($month->revenue) }}</span>
                        <br>
                        <small class="text-muted">({{ $month->count }} {{ __('Subscription') }})</small>
                    </div>
                </div>
            @endforeach
            </div>
        </x-card>
    @endif

@endsection

@section('scripts')
<script>
    $(document).ready(() => {
        let inputs = {
            users: $(".users-select"),
            plans: $(".plans-select"),
        };

        lazySelect2Ajax(inputs.users, `{{ route('ajax.get-users') }}`, false, `{{ $request['user_id'] ?? '' }}` || null)
        lazySelect2Ajax(inputs.plans, `{{ route('ajax.get-plans') }}`, false, `{{ $request['plan_id'] ?? '' }}` || null)
    });

</script>
@endsection
