<?php

namespace App\Http\Controllers\API\Dashboard;

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

class DashboardController extends Controller
{
    use ApiResponse;

    /**
     * جلب إحصائيات لوحة التحكم
     */
    public function getStatistics(Request $request)
    {
        try {
            // إحصائيات المستخدمين
            $totalUsers = User::count();
            $activeUsers = User::where('status', 'active')->count();
            $inactiveUsers = User::where('status', 'inactive')->count();

            // إحصائيات العقود
            $totalContracts = Contract::count();
            $pendingContracts = Contract::where('contract_status', 'pending')->count();
            $draftContracts = Contract::where('contract_status', 'draft')->count();
            $approvedContracts = Contract::where('contract_status', 'approved')->count();
            $rejectedContracts = Contract::where('contract_status', 'rejected')->count();
            $cancelledContracts = Contract::where('contract_status', 'cancelled')->count();
            $activeContracts = Contract::where('is_active', true)->count();

            // العقود حسب الشهر (آخر 6 أشهر)
            $contractsByMonth = $this->getContractsByMonth(6);

            // النشاط الأخير (آخر 10 عقود محدثة)
            $recentActivity = $this->getRecentActivity(10);

            // إحصائيات إضافية
            $todayContracts = Contract::whereDate('created_at', today())->count();
            $currentMonth = now()->month;
            $currentYear = now()->year;
            $thisMonthContracts = Contract::whereMonth('created_at', $currentMonth)
                ->whereYear('created_at', $currentYear)
                ->count();
            $lastMonthDate = now()->subMonth();
            $lastMonthContracts = Contract::whereMonth('created_at', $lastMonthDate->month)
                ->whereYear('created_at', $lastMonthDate->year)
                ->count();

            $monthlyChange = $lastMonthContracts > 0 
                ? round((($thisMonthContracts - $lastMonthContracts) / $lastMonthContracts) * 100, 2)
                : 0;

            $data = [
                'users' => [
                    'total' => $totalUsers,
                    'active' => $activeUsers,
                    'inactive' => $inactiveUsers,
                ],
                'contracts' => [
                    'total' => $totalContracts,
                    'pending' => $pendingContracts,
                    'draft' => $draftContracts,
                    'approved' => $approvedContracts,
                    'rejected' => $rejectedContracts,
                    'cancelled' => $cancelledContracts,
                    'active' => $activeContracts,
                    'today' => $todayContracts,
                    'this_month' => $thisMonthContracts,
                    'last_month' => $lastMonthContracts,
                    'monthly_change' => $monthlyChange,
                ],
                'contracts_by_month' => $contractsByMonth,
                'recent_activity' => $recentActivity,
            ];

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

    /**
     * جلب العقود حسب الشهر
     */
    private function getContractsByMonth($months = 6)
    {
        $monthsData = [];
        $currentDate = Carbon::now();

        for ($i = $months - 1; $i >= 0; $i--) {
            $monthDate = $currentDate->copy()->subMonths($i);
            $monthStart = $monthDate->copy()->startOfMonth();
            $monthEnd = $monthDate->copy()->endOfMonth();

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

            $monthsData[] = [
                'month' => $monthDate->format('Y-m'),
                'month_name' => $monthDate->locale('ar')->translatedFormat('F'),
                'month_name_en' => $monthDate->format('F'),
                'count' => $count,
            ];
        }

        return $monthsData;
    }

    /**
     * جلب النشاط الأخير
     */
    private function getRecentActivity($limit = 10)
    {
        $activities = Contract::with(['createdBy:id,name,email'])
            ->orderBy('updated_at', 'desc')
            ->limit($limit)
            ->get()
            ->map(function ($contract) {
                $statusLabels = [
                    'pending' => 'قيد الانتظار',
                    'draft' => 'مسودة',
                    'approved' => 'معتمد',
                    'rejected' => 'مرفوض',
                    'cancelled' => 'ملغى',
                ];

                $statusLabelsEn = [
                    'pending' => 'Pending',
                    'draft' => 'Draft',
                    'approved' => 'Approved',
                    'rejected' => 'Rejected',
                    'cancelled' => 'Cancelled',
                ];

                $createdAt = Carbon::parse($contract->created_at);
                $now = Carbon::now();
                $diffInMinutes = $createdAt->diffInMinutes($now);
                $diffInHours = $createdAt->diffInHours($now);
                $diffInDays = $createdAt->diffInDays($now);

                if ($diffInMinutes < 60) {
                    $timeText = $diffInMinutes . ' دقيقة';
                    $timeTextEn = $diffInMinutes . ' minutes';
                } elseif ($diffInHours < 24) {
                    $timeText = $diffInHours . ' ساعة';
                    $timeTextEn = $diffInHours . ' hours';
                } else {
                    $timeText = $diffInDays . ' يوم';
                    $timeTextEn = $diffInDays . ' days';
                }

                return [
                    'id' => $contract->id,
                    'type' => 'contract',
                    'contract_number' => $contract->contract_number,
                    'contract_status' => $contract->contract_status,
                    'status_label' => $statusLabels[$contract->contract_status] ?? $contract->contract_status,
                    'status_label_en' => $statusLabelsEn[$contract->contract_status] ?? $contract->contract_status,
                    'created_by' => $contract->createdBy ? [
                        'id' => $contract->createdBy->id,
                        'name' => $contract->createdBy->name,
                        'email' => $contract->createdBy->email,
                    ] : null,
                    'created_at' => $contract->created_at,
                    'updated_at' => $contract->updated_at,
                    'time_ago' => $timeText,
                    'time_ago_en' => $timeTextEn,
                ];
            });

        return $activities;
    }
}
