<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\PlatformFee;
use App\Models\Restaurant;
use App\Models\GasOffice;
use App\Services\PlatformFeeService;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class PlatformFeesController extends Controller
{
    /**
     * عرض قائمة مقدمي الخدمات مع إحصائيات الأجور
     */
    public function index(Request $request)
    {
        $type = $request->get('type', 'all'); // all, restaurants, gas_offices
        
        // إحصائيات عامة
        $totalFees = PlatformFee::sum('platform_fee');
        $dailyFeesData = PlatformFeeService::getDailyFees();
        $monthlyFeesData = PlatformFeeService::getMonthlyFees();
        $yearlyFeesData = PlatformFeeService::getYearlyFees();
        $dailyFees = $dailyFeesData['total'] ?? 0;
        $monthlyFees = $monthlyFeesData['total'] ?? 0;
        $yearlyFees = $yearlyFeesData['total'] ?? 0;
        
        // قائمة المطاعم مع إحصائيات
        $today = Carbon::today()->format('Y-m-d');
        $currentMonth = Carbon::now()->month;
        $currentYear = Carbon::now()->year;
        
        // إحصائيات المطاعم عبر استعلام فرعي (متوافق مع ONLY_FULL_GROUP_BY)
        $restaurantFeesSub = DB::table('platform_fees')
            ->where('platform_fees.service_provider_type', '=', 'restaurant')
            ->select(
                'platform_fees.service_provider_id',
                DB::raw('COALESCE(SUM(platform_fees.platform_fee), 0) as total_fees'),
                DB::raw("COALESCE(SUM(CASE WHEN DATE(platform_fees.created_at) = '{$today}' THEN platform_fees.platform_fee ELSE 0 END), 0) as daily_fees"),
                DB::raw("COALESCE(SUM(CASE WHEN MONTH(platform_fees.created_at) = {$currentMonth} AND YEAR(platform_fees.created_at) = {$currentYear} THEN platform_fees.platform_fee ELSE 0 END), 0) as monthly_fees"),
                DB::raw("COALESCE(SUM(CASE WHEN YEAR(platform_fees.created_at) = {$currentYear} THEN platform_fees.platform_fee ELSE 0 END), 0) as yearly_fees"),
                DB::raw('COUNT(platform_fees.id) as orders_count')
            )
            ->groupBy('platform_fees.service_provider_id');

        $restaurantsQuery = Restaurant::query()
            ->leftJoinSub($restaurantFeesSub, 'fee_stats', 'restaurants.id', '=', 'fee_stats.service_provider_id')
            ->select(
                'restaurants.*',
                DB::raw('COALESCE(fee_stats.total_fees, 0) as total_fees'),
                DB::raw('COALESCE(fee_stats.daily_fees, 0) as daily_fees'),
                DB::raw('COALESCE(fee_stats.monthly_fees, 0) as monthly_fees'),
                DB::raw('COALESCE(fee_stats.yearly_fees, 0) as yearly_fees'),
                DB::raw('COALESCE(fee_stats.orders_count, 0) as orders_count')
            );

        // إحصائيات مكاتب الغاز عبر استعلام فرعي (متوافق مع ONLY_FULL_GROUP_BY)
        $gasFeesSub = DB::table('platform_fees')
            ->where('platform_fees.service_provider_type', '=', 'gas_office')
            ->select(
                'platform_fees.service_provider_id',
                DB::raw('COALESCE(SUM(platform_fees.platform_fee), 0) as total_fees'),
                DB::raw("COALESCE(SUM(CASE WHEN DATE(platform_fees.created_at) = '{$today}' THEN platform_fees.platform_fee ELSE 0 END), 0) as daily_fees"),
                DB::raw("COALESCE(SUM(CASE WHEN MONTH(platform_fees.created_at) = {$currentMonth} AND YEAR(platform_fees.created_at) = {$currentYear} THEN platform_fees.platform_fee ELSE 0 END), 0) as monthly_fees"),
                DB::raw("COALESCE(SUM(CASE WHEN YEAR(platform_fees.created_at) = {$currentYear} THEN platform_fees.platform_fee ELSE 0 END), 0) as yearly_fees"),
                DB::raw('COUNT(platform_fees.id) as orders_count')
            )
            ->groupBy('platform_fees.service_provider_id');

        $gasOfficesQuery = GasOffice::query()
            ->leftJoinSub($gasFeesSub, 'fee_stats', 'gas_offices.id', '=', 'fee_stats.service_provider_id')
            ->select(
                'gas_offices.*',
                DB::raw('COALESCE(fee_stats.total_fees, 0) as total_fees'),
                DB::raw('COALESCE(fee_stats.daily_fees, 0) as daily_fees'),
                DB::raw('COALESCE(fee_stats.monthly_fees, 0) as monthly_fees'),
                DB::raw('COALESCE(fee_stats.yearly_fees, 0) as yearly_fees'),
                DB::raw('COALESCE(fee_stats.orders_count, 0) as orders_count')
            );
        
        // تطبيق البحث
        if ($request->filled('search')) {
            $search = $request->search;
            $restaurantsQuery->where('name', 'like', '%' . $search . '%');
            $gasOfficesQuery->where('name', 'like', '%' . $search . '%');
        }
        
        // تطبيق النوع
        if ($type === 'restaurants') {
            $restaurants = $restaurantsQuery->paginate(20);
            $gasOffices = collect();
        } elseif ($type === 'gas_offices') {
            $gasOffices = $gasOfficesQuery->paginate(20);
            $restaurants = collect();
        } else {
            $restaurants = $restaurantsQuery->paginate(10);
            $gasOffices = $gasOfficesQuery->paginate(10);
        }
        
        return view('admin.platform_fees.index', compact(
            'restaurants',
            'gasOffices',
            'type',
            'totalFees',
            'dailyFees',
            'monthlyFees',
            'yearlyFees'
        ));
    }

    /**
     * عرض تفاصيل إحصائيات مقدم خدمة معين
     */
    public function show(Request $request, $type, $id)
    {
        $period = $request->get('period', 'month'); // week, month, year, custom
        
        if ($type === 'restaurant') {
            $provider = Restaurant::findOrFail($id);
            $providerType = 'restaurant';
            $providerName = $provider->name;
        } elseif ($type === 'gas_office') {
            $provider = GasOffice::findOrFail($id);
            $providerType = 'gas_office';
            $providerName = $provider->name;
        } else {
            abort(404);
        }
        
        // تحديد الفترة
        $startDate = $request->get('start_date');
        $endDate = $request->get('end_date');
        
        if (!$startDate || !$endDate) {
            if ($period == 'week') {
                $startDate = Carbon::now()->startOfWeek()->format('Y-m-d');
                $endDate = Carbon::now()->endOfWeek()->format('Y-m-d');
            } elseif ($period == 'month') {
                $startDate = Carbon::now()->startOfMonth()->format('Y-m-d');
                $endDate = Carbon::now()->endOfMonth()->format('Y-m-d');
            } else {
                $startDate = Carbon::now()->startOfYear()->format('Y-m-d');
                $endDate = Carbon::now()->endOfYear()->format('Y-m-d');
            }
        }
        
        // إحصائيات الفترة
        $feesStats = PlatformFeeService::getProviderFees($id, $providerType, $startDate, $endDate);
        
        // الأجور اليومية
        $dailyFees = PlatformFee::where('service_provider_id', $id)
            ->where('service_provider_type', $providerType)
            ->whereDate('created_at', '>=', $startDate)
            ->whereDate('created_at', '<=', $endDate)
            ->select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('SUM(platform_fee) as total_fees'),
                DB::raw('COUNT(*) as orders_count')
            )
            ->groupBy('date')
            ->orderBy('date')
            ->get();
        
        // قائمة الأجور
        $fees = PlatformFee::where('service_provider_id', $id)
            ->where('service_provider_type', $providerType)
            ->whereDate('created_at', '>=', $startDate)
            ->whereDate('created_at', '<=', $endDate)
            ->with('order')
            ->latest()
            ->paginate(20);
        
        return view('admin.platform_fees.show', compact(
            'provider',
            'providerType',
            'providerName',
            'type',
            'id',
            'period',
            'startDate',
            'endDate',
            'feesStats',
            'dailyFees',
            'fees'
        ));
    }
}
