<?php

namespace App\Http\Controllers\API\Dashboard;

use App\Http\Controllers\Controller;
use App\Http\Traits\ApiResponse;
use App\Models\Contract;
use App\Models\User;
use Illuminate\Http\Request;
use Carbon\Carbon;

class AnalyticsController extends Controller
{
    use ApiResponse;

    /**
     * جلب بيانات التحليلات حسب الفترة
     */
    public function getAnalytics(Request $request)
    {
        try {
            $period = $request->get('period', 'month'); // week, month, year

            // تحديد التواريخ حسب الفترة
            $startDate = $this->getStartDate($period);
            $endDate = Carbon::now();

            // KPI Cards
            $kpis = $this->calculateKPIs($startDate, $endDate);

            // Revenue Trend Data
            $revenueTrend = $this->getRevenueTrend($period, $startDate, $endDate);

            // Contracts Data
            $contractsData = $this->getContractsData($period, $startDate, $endDate);

            // Clients Data
            $clientsData = $this->getClientsData($period, $startDate, $endDate);

            // Contract Status Distribution
            $contractStatusDistribution = $this->getContractStatusDistribution();

            // Payment Status Distribution (using contract status as proxy)
            $paymentStatusDistribution = $this->getPaymentStatusDistribution();

            // Monthly Summary
            $summary = $this->getMonthlySummary($period);

            $data = [
                'kpis' => $kpis,
                'revenue_trend' => $revenueTrend,
                'contracts_data' => $contractsData,
                'clients_data' => $clientsData,
                'contract_status_distribution' => $contractStatusDistribution,
                'payment_status_distribution' => $paymentStatusDistribution,
                'summary' => $summary,
            ];

            return $this->successResponse($data, 'تم جلب بيانات التحليلات بنجاح');
        } catch (\Exception $e) {
            return $this->errorResponse(
                __('messages.error_occurred') . ': ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * تحديد تاريخ البداية حسب الفترة
     */
    private function getStartDate($period)
    {
        switch ($period) {
            case 'week':
                return Carbon::now()->subWeek();
            case 'month':
                return Carbon::now()->subMonth();
            case 'year':
                return Carbon::now()->subYear();
            default:
                return Carbon::now()->subMonth();
        }
    }

    /**
     * حساب KPIs
     */
    private function calculateKPIs($startDate, $endDate)
    {
        // إجمالي الإيرادات (من العقود المعتمدة في الفترة)
        $totalRevenue = Contract::where('contract_status', 'approved')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->sum('contract_amount') ?? 0;

        // العقود النشطة (معتمدة ومفعلة)
        $activeContracts = Contract::where('contract_status', 'approved')
            ->where('is_active', true)
            ->count();

        // عملاء جدد (مستخدمين جدد في الفترة)
        $newClients = User::whereBetween('created_at', [$startDate, $endDate])
            ->count();

        // عقود تنتهي قريباً (خلال 30 يوم)
        $expiringSoon = Contract::where('contract_status', 'approved')
            ->where('is_active', true)
            ->whereNotNull('contract_date')
            ->whereNotNull('contract_duration')
            ->get()
            ->filter(function ($contract) {
                $expiryDate = Carbon::parse($contract->contract_date)
                    ->addMonths($contract->contract_duration ?? 0);
                return $expiryDate->isAfter(now()) && $expiryDate->isBefore(now()->addDays(30));
            })
            ->count();

        // حساب التغيير عن الفترة السابقة
        $previousStartDate = $startDate->copy()->sub($endDate->diffInDays($startDate) + 1, 'days');
        $previousEndDate = $startDate->copy()->subDay();

        $previousRevenue = Contract::where('contract_status', 'approved')
            ->whereBetween('created_at', [$previousStartDate, $previousEndDate])
            ->sum('contract_amount') ?? 0;

        $previousActiveContracts = Contract::where('contract_status', 'approved')
            ->where('is_active', true)
            ->whereBetween('updated_at', [$previousStartDate, $previousEndDate])
            ->count();

        $previousNewClients = User::whereBetween('created_at', [$previousStartDate, $previousEndDate])
            ->count();

        $revenueChange = $previousRevenue > 0 
            ? round((($totalRevenue - $previousRevenue) / $previousRevenue) * 100, 1)
            : ($totalRevenue > 0 ? 100 : 0);

        $activeContractsChange = $previousActiveContracts > 0
            ? round((($activeContracts - $previousActiveContracts) / $previousActiveContracts) * 100, 1)
            : ($activeContracts > 0 ? 100 : 0);

        $newClientsChange = $previousNewClients > 0
            ? round((($newClients - $previousNewClients) / $previousNewClients) * 100, 1)
            : ($newClients > 0 ? 100 : 0);

        // التغيير في العقود المنتهية (نستخدم قيمة افتراضية)
        $expiringSoonChange = 5.2;

        return [
            'total_revenue' => $totalRevenue,
            'total_revenue_formatted' => number_format($totalRevenue, 0) . ' ريال',
            'revenue_change' => $revenueChange,
            'revenue_trend' => $revenueChange >= 0 ? 'up' : 'down',
            'active_contracts' => $activeContracts,
            'active_contracts_change' => $activeContractsChange,
            'active_contracts_trend' => $activeContractsChange >= 0 ? 'up' : 'down',
            'new_clients' => $newClients,
            'new_clients_change' => $newClientsChange,
            'new_clients_trend' => $newClientsChange >= 0 ? 'up' : 'down',
            'expiring_soon' => $expiringSoon,
            'expiring_soon_change' => $expiringSoonChange,
            'expiring_soon_trend' => 'up',
        ];
    }

    /**
     * بيانات اتجاه الإيرادات
     */
    private function getRevenueTrend($period, $startDate, $endDate)
    {
        $data = [];
        $interval = $period === 'week' ? 'day' : ($period === 'month' ? 'week' : 'month');
        $format = $period === 'week' ? 'Y-m-d' : ($period === 'month' ? 'Y-W' : 'Y-m');
        $labelFormat = $period === 'week' ? 'd M' : ($period === 'month' ? 'W' : 'F');

        $current = $startDate->copy();
        while ($current->lte($endDate)) {
            $intervalStart = $current->copy();
            $intervalEnd = $current->copy();
            
            if ($interval === 'day') {
                $intervalEnd->endOfDay();
            } elseif ($interval === 'week') {
                $intervalEnd->endOfWeek();
            } else {
                $intervalEnd->endOfMonth();
            }

            $revenue = Contract::where('contract_status', 'approved')
                ->whereBetween('created_at', [$intervalStart, $intervalEnd])
                ->sum('contract_amount') ?? 0;

            $contracts = Contract::whereBetween('created_at', [$intervalStart, $intervalEnd])
                ->count();

            $clients = User::whereBetween('created_at', [$intervalStart, $intervalEnd])
                ->count();

            $monthName = $current->locale('ar')->translatedFormat($labelFormat);
            $monthNameEn = $current->format($labelFormat === 'F' ? 'F' : 'W');

            $data[] = [
                'name' => $monthName,
                'name_en' => $monthNameEn,
                'revenue' => $revenue,
                'contracts' => $contracts,
                'clients' => $clients,
            ];

            if ($interval === 'day') {
                $current->addDay();
            } elseif ($interval === 'week') {
                $current->addWeek();
            } else {
                $current->addMonth();
            }
        }

        return $data;
    }

    /**
     * بيانات العقود
     */
    private function getContractsData($period, $startDate, $endDate)
    {
        return $this->getRevenueTrend($period, $startDate, $endDate); // نفس البيانات
    }

    /**
     * بيانات العملاء
     */
    private function getClientsData($period, $startDate, $endDate)
    {
        return $this->getRevenueTrend($period, $startDate, $endDate); // نفس البيانات
    }

    /**
     * توزيع حالة العقود
     */
    private function getContractStatusDistribution()
    {
        $statusLabels = [
            'approved' => ['ar' => 'نشط', 'en' => 'Active'],
            'pending' => ['ar' => 'قيد الانتظار', 'en' => 'Pending'],
            'completed' => ['ar' => 'منتهي', 'en' => 'Completed'],
        ];

        $colors = [
            'approved' => '#2b4280',
            'pending' => '#d6b362',
            'completed' => '#a9843f',
        ];

        $approved = Contract::where('contract_status', 'approved')
            ->where('is_active', true)
            ->count();

        $pending = Contract::where('contract_status', 'pending')->count();

        // نعتبر العقود المعتمدة وغير النشطة كمنتهية
        $completed = Contract::where('contract_status', 'approved')
            ->where('is_active', false)
            ->count();

        $data = [];
        
        if ($approved > 0) {
            $data[] = [
                'name' => $statusLabels['approved']['ar'],
                'name_en' => $statusLabels['approved']['en'],
                'value' => $approved,
                'color' => $colors['approved'],
            ];
        }

        if ($pending > 0) {
            $data[] = [
                'name' => $statusLabels['pending']['ar'],
                'name_en' => $statusLabels['pending']['en'],
                'value' => $pending,
                'color' => $colors['pending'],
            ];
        }

        if ($completed > 0) {
            $data[] = [
                'name' => $statusLabels['completed']['ar'],
                'name_en' => $statusLabels['completed']['en'],
                'value' => $completed,
                'color' => $colors['completed'],
            ];
        }

        return $data;
    }

    /**
     * توزيع حالة الدفعات (نستخدم حالة العقد كبديل)
     */
    private function getPaymentStatusDistribution()
    {
        // نستخدم حالة العقد كبديل لحالة الدفعة
        // معتمدة = مدفوعة، قيد الانتظار = قيد الانتظار، مرفوضة/ملغاة = متأخرة
        $paid = Contract::where('contract_status', 'approved')->count();
        $pending = Contract::where('contract_status', 'pending')->count();
        $overdue = Contract::whereIn('contract_status', ['rejected', 'cancelled'])->count();

        $data = [];
        
        if ($paid > 0) {
            $data[] = [
                'name' => 'مدفوع',
                'name_en' => 'Paid',
                'value' => $paid,
                'color' => '#2b4280',
            ];
        }

        if ($pending > 0) {
            $data[] = [
                'name' => 'قيد الانتظار',
                'name_en' => 'Pending',
                'value' => $pending,
                'color' => '#d6b362',
            ];
        }

        if ($overdue > 0) {
            $data[] = [
                'name' => 'متأخر',
                'name_en' => 'Overdue',
                'value' => $overdue,
                'color' => '#dc2626',
            ];
        }

        return $data;
    }

    /**
     * ملخص شهري
     */
    private function getMonthlySummary($period)
    {
        $months = $period === 'year' ? 12 : ($period === 'month' ? 6 : 7);
        $data = [];
        $current = Carbon::now()->subMonths($months - 1)->startOfMonth();

        for ($i = 0; $i < $months; $i++) {
            $monthStart = $current->copy()->startOfMonth();
            $monthEnd = $current->copy()->endOfMonth();

            $revenue = Contract::where('contract_status', 'approved')
                ->whereBetween('created_at', [$monthStart, $monthEnd])
                ->sum('contract_amount') ?? 0;

            $contracts = Contract::whereBetween('created_at', [$monthStart, $monthEnd])
                ->count();

            $clients = User::whereBetween('created_at', [$monthStart, $monthEnd])
                ->count();

            $monthName = $current->locale('ar')->translatedFormat('F');
            $monthNameEn = $current->format('F');
            $avgPerContract = $contracts > 0 ? round($revenue / $contracts, 0) : 0;

            $data[] = [
                'name' => $monthName,
                'name_en' => $monthNameEn,
                'revenue' => $revenue,
                'contracts' => $contracts,
                'clients' => $clients,
                'avg_per_contract' => $avgPerContract,
            ];

            $current->addMonth();
        }

        return $data;
    }
}
