<?php

namespace App\Http\Controllers;

use App\Models\UserProfile;
use App\Models\Assignment;
use App\Models\Perizinan;
use App\Models\Presensi;
use App\Models\Agenda;
use App\Models\PemesananItem;
use App\Models\Pemesanan;
use App\Models\Service;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MonitoringController extends Controller
{
    public function getUser(UserProfile $userProfile)
    {
        try {
            $allUser = $userProfile->select('id', 'name', 'user_type_id')->get();
            return response()->json($allUser);
        } catch (\Throwable $th) {
            return response()->json(['error' => 'An error occurred'], 500);
        }
    }

    public function getRekap(UserProfile $userProfile, Assignment $assignment, Perizinan $perizinan, Presensi $presensi, Agenda $agenda)
    {
        try {
            $totalUsers = $userProfile->count();
            $totalAssignments = $assignment->where('status', '!=', 'Done')->count();
            $totalCuti = $perizinan->where('tipe', 'cuti')->count();
            $totalIzin = $perizinan->where('tipe', 'izin')->count();
            // $totalPerizinan = $totalCuti + $totalIzin;
	         $totalPerizinanValid = $perizinan->where('status', '!=', 'rejected')->count();

            
            $userCutiDetails = $perizinan
                ->where('tipe', 'cuti')
            ->where('status', '!=', 'rejected')
            ->select('nama_pemohon', 'tipe')
            ->get();

		
            $userIzinDetails = $perizinan
                ->where('tipe', 'izin')
            ->where('status', '!=', 'rejected')
            ->select('nama_pemohon', 'tipe')
            ->get();


            $today = now()->toDateString();
            $totalPresensiToday = $presensi->whereDate('created_at', $today)->count();
            $totalTerlambat = $presensi->whereDate('created_at', $today)->where('status', 'Late')->count();
            $totalAgenda = $agenda->count();
            

            // BACKUP PENTING

            // $totalOrders = Pemesanan::count(); // Hitung total order

            // $statusCount = Pemesanan::select('status', DB::raw('count(*) as total'))
            //     ->groupBy('status')
            //     ->pluck('total', 'status');

            // $completedOrders = Pemesanan::where('status', 'done')
            //     ->with(['pemesananItems' => function ($query) {
            //         $query->select('id', 'service_id', 'quantity');
            //     }])
            //     ->get();

            // $serviceCount = [];

            // foreach ($completedOrders as $order) {
            //     foreach ($order->pemesananItems as $item) {
            //         $serviceIds = json_decode($item->service_id);
            //         $quantities = json_decode($item->quantity);

            //         if (is_array($serviceIds) && is_array($quantities) && count($serviceIds) === count($quantities)) {
            //             foreach ($serviceIds as $index => $serviceId) {
            //                 $serviceCount[$serviceId] = ($serviceCount[$serviceId] ?? 0) + $quantities[$index];
            //             }
            //         } else {
            //             Log::warning("Invalid JSON data in PemesananItem ID: {$item->id}", [
            //                 'service_id' => $item->service_id,
            //                 'quantity' => $item->quantity,
            //             ]);
            //         }
            //     }
            // }

            // $services = Service::whereIn('id', array_keys($serviceCount))->pluck('name', 'id');

            // $formattedServiceCount = [];
            // foreach ($serviceCount as $serviceId => $count) {
            //     if (isset($services[$serviceId])) {
            //         $formattedServiceCount[$services[$serviceId]] = $count;
            //     }
            // }

            $totalOrders = Pemesanan::count();

            $statusCount = Pemesanan::select('status', DB::raw('count(*) as total'))
                ->groupBy('status')
                ->pluck('total', 'status');

            $completedOrders = Pemesanan::where('status', 'done')
                ->with('pemesananItem')
                ->get();

                // $completedOrders = Pemesanan::where('status', 'done')
                // ->with('pemesananItem') // Nama relasi sekarang 'pemesananItem' (tunggal)
                // ->get();
            
            // dump("Completed Orders (toArray):", $completedOrders->toArray()); // Sangat penting!
            
            $serviceCount = [];
            
            foreach ($completedOrders as $order) {
                // dump("Order ID:", $order->id);
                // dump("Order pemesanan_id:", $order->pemesanan_id); // Tambahkan ini
                // dump("Order Status:", $order->status);
            
                // if ($order->pemesananItem === null) { // Sekarang cek null, bukan isEmpty()
                //     dump("No item found for this order!");
                //     continue;
                // }
            
                $item = $order->pemesananItem; // Akses item melalui relasi
            
                // dump("Raw service_id (before decode):", $item->service_id);
                $serviceIds = json_decode($item->service_id);
                // dump("Service IDs (after decode):", $serviceIds);
            
                // dump("Raw quantity (before decode):", $item->quantity);
                $quantities = json_decode($item->quantity);
                // dump("Quantities (after decode):", $quantities);
            
                if (is_array($serviceIds) && is_array($quantities) && count($serviceIds) === count($quantities)) {
                    foreach ($serviceIds as $index => $serviceId) {
                        if (is_numeric($serviceId)) {
                            $quantity = $quantities[$index];
                            $serviceCount[$serviceId] = ($serviceCount[$serviceId] ?? 0) + $quantity;
                        } else {
                            Log::warning("Invalid service_id (not numeric)...");
                        }
                    }
                } else {
                    Log::warning("Invalid JSON data...");
                }
            }
            
            // dump("Service Count:", $serviceCount);
            
            $services = Service::whereIn('id', array_keys($serviceCount))->get();
            // dump("Services:", $services->toArray()); // Debug: tampilkan data service yang ditemukan

            $formattedServiceCount = [];
            foreach ($serviceIds as $index => $serviceId) {
                if (is_numeric($serviceId)) {
                    $serviceId = (int) $serviceId; 
                    $quantity = $quantities[$index];
                    $serviceCount[$serviceId] = ($serviceCount[$serviceId] ?? 0) + $quantity;
                } 
            }

            // dump("Service Count:", $serviceCount);

            $services = Service::whereIn('id', array_keys($serviceCount))->get();
            // dump("Services:", $services->toArray());


            foreach ($services as $service) { // Loop melalui Collection of Models
                $serviceId = $service->id;
                $serviceName = $service->name;

                if (isset($serviceCount[$serviceId])) {
                    $formattedServiceCount[$serviceName] = $serviceCount[$serviceId];
                }
            }

            return response()->json([
                'status' => 'success',
                'message' => 'Recap data retrieved successfully',
                'data' => [
                    'users' => [
                        'total' => $totalUsers
                    ],
                    'assignments' => [
                        'total' => $totalAssignments
                    ],
                    'perizinan' => [
                        'total' => $totalPerizinanValid,
                    'today' => [
                        'izin' => $totalIzin,
                        'cuti' => $totalCuti
                    ],
                    'details' => [
                        'cuti' => $userCutiDetails,
                        'izin' => $userIzinDetails
                    ]
                    
                    ],
                    'presensi' => [
                        'today' => [
                            'total' => $totalPresensiToday,
                            'terlambat' => $totalTerlambat
                        ]
                    ],
                    'agenda' => [
                        'total' => $totalAgenda
                    ],
                    'pemesanan' => [
                        'total_orders' => $totalOrders,
                        'status_count' => $statusCount,
                        'completed_services' => $formattedServiceCount,
                ],
                ]
            ], 200, [], JSON_PRETTY_PRINT);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to retrieve recap data', 'error' => $e->getMessage()], 500);
        }
    }

    public function getLatestAssignments(Assignment $assignment)
    {
        try {
            // Mengambil maksimal 3 data terbaru dari Assignment
            // $latestAssignments = $assignment->orderBy('created_at', 'desc')->take(3)->get(['title', 'status', 'deadline']);
            $latestAssignments = $assignment->where('status', '!=', 'Done')->orderBy('created_at', 'desc')->take(3)->get(['title', 'status', 'deadline']);

            return response()->json([
                'status' => 'success',
                'message' => 'Latest assignments retrieved successfully',
                'data' => $latestAssignments
            ], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to retrieve latest assignments', 'error' => $e->getMessage()], 500);
        }
    }

    public function getUpcomingOrLatest(Agenda $agenda)
    {
        try {
            $today = now();

            // Mengambil 3 agenda yang mendekati hari ini
            $upcomingAgendas = $agenda->where('start_time', '>=', $today)
                ->orderBy('start_time', 'asc')
                ->take(3)
                ->get(['start_time', 'end_time', 'agenda_name']);

            // Jika tidak ada agenda yang akan datang, ambil 3 agenda terbaru
            if ($upcomingAgendas->isEmpty()) {
                $upcomingAgendas = $agenda->orderBy('created_at', 'desc')
                    ->take(3)
                    ->get(['start_time', 'end_time', 'agenda_name']);
            }

            return response()->json([
                'status' => 'success',
                'message' => 'Agendas retrieved successfully',
                'data' => $upcomingAgendas
            ], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to retrieve agendas', 'error' => $e->getMessage()], 500);
        }
    }

    
}
