<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\Permission;
use App\Models\User;
use App\Exports\AttendanceExport;
use App\Exports\PermissionExport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class ReportController extends Controller
{
    public function attendanceReport(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'user_id' => 'nullable|exists:users,id',
            'status' => 'nullable|in:pending,accepted,rejected',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $query = Attendance::with(['user.profile', 'location'])
            ->whereBetween('date', [$request->start_date, $request->end_date]);

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $attendances = $query->orderBy('date', 'desc')->orderBy('time', 'desc')->get();

        $summary = $attendances->groupBy('user_id')->map(function ($userAttendances) {
            $user = $userAttendances->first()->user;
            $dates = $userAttendances->groupBy('date');

            return [
                'user' => $user,
                'total_days' => $dates->count(),
                'present_days' => $dates->filter(function ($dayAttendances) {
                    return $dayAttendances->where('status', 'accepted')->count() > 0;
                })->count(),
                'attendances' => $userAttendances
            ];
        });

        return response()->json([
            'message' => 'Laporan absensi berhasil diambil.',
            'data' => [
                'summary' => $summary->values(),
                'details' => $attendances,
                'period' => [
                    'start_date' => $request->start_date,
                    'end_date' => $request->end_date
                ]
            ]
        ], 200);
    }

    public function permissionReport(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'user_id' => 'nullable|exists:users,id',
            'status' => 'nullable|in:pending,accepted,rejected',
            'category' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $query = Permission::with(['user.profile', 'approver'])
            ->where(function ($q) use ($request) {
                $q->whereBetween('start_date', [$request->start_date, $request->end_date])
                  ->orWhereBetween('end_date', [$request->start_date, $request->end_date]);
            });

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('category')) {
            $query->where('category', $request->category);
        }

        $permissions = $query->orderBy('created_at', 'desc')->get();

        $categoryStats = $permissions->groupBy('category')->map(function ($categoryPermissions, $category) {
            return [
                'category' => $category,
                'total' => $categoryPermissions->count(),
                'approved' => $categoryPermissions->where('status', 'accepted')->count(),
                'rejected' => $categoryPermissions->where('status', 'rejected')->count(),
                'pending' => $categoryPermissions->where('status', 'pending')->count(),
                'total_days' => $categoryPermissions->sum('duration'),
            ];
        });

        return response()->json([
            'message' => 'Laporan izin berhasil diambil.',
            'data' => [
                'summary' => $categoryStats->values(),
                'details' => $permissions,
                'period' => [
                    'start_date' => $request->start_date,
                    'end_date' => $request->end_date
                ]
            ]
        ], 200);
    }

    public function exportAttendanceExcel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'user_id' => 'nullable|exists:users,id',
            'status' => 'nullable|in:pending,accepted,rejected',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $filename = 'laporan_absensi_' . $request->start_date . '_' . $request->end_date . '.xlsx';

        return Excel::download(new AttendanceExport($request->all()), $filename);
    }

    public function exportAttendancePdf(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'user_id' => 'nullable|exists:users,id',
            'status' => 'nullable|in:pending,accepted,rejected',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $query = Attendance::with(['user.profile', 'location'])
            ->whereBetween('date', [$request->start_date, $request->end_date]);

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $attendances = $query->orderBy('date', 'desc')->orderBy('time', 'desc')->get();

        $pdf = Pdf::loadView('reports.attendance', [
            'attendances' => $attendances,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date
        ]);

        $filename = 'laporan_absensi_' . $request->start_date . '_' . $request->end_date . '.pdf';

        return $pdf->download($filename);
    }

    public function exportPermissionExcel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'user_id' => 'nullable|exists:users,id',
            'status' => 'nullable|in:pending,accepted,rejected',
            'category' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $filename = 'laporan_izin_' . $request->start_date . '_' . $request->end_date . '.xlsx';

        return Excel::download(new PermissionExport($request->all()), $filename);
    }

    public function exportPermissionPdf(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'user_id' => 'nullable|exists:users,id',
            'status' => 'nullable|in:pending,accepted,rejected',
            'category' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ], 422);
        }

        $query = Permission::with(['user.profile', 'approver'])
            ->where(function ($q) use ($request) {
                $q->whereBetween('start_date', [$request->start_date, $request->end_date])
                ->orWhereBetween('end_date', [$request->start_date, $request->end_date]);
            });

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('category')) {
            $query->where('category', $request->category);
        }

        $permissions = $query->orderBy('created_at', 'desc')->get();

        $pdf = Pdf::loadView('reports.permission', [
            'permissions' => $permissions,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date
        ]);

        $filename = 'laporan_izin_' . $request->start_date . '_' . $request->end_date . '.pdf';

        return $pdf->download($filename);
    }

    public function dashboard(Request $request)
    {
        $today = now()->toDateString();
        $thisMonth = now()->format('Y-m');

        $stats = [
            'users' => [
                'total' => User::count(),
                'admin' => User::where('role', 'admin')->count(),
                'employee' => User::where('role', 'karyawan')->count(),
            ],
            'attendance' => [
                'today' => Attendance::whereDate('date', $today)->count(),
                'today_present' => Attendance::whereDate('date', $today)->where('status', 'accepted')->count(),
                'today_pending' => Attendance::whereDate('date', $today)->where('status', 'pending')->count(),
                'this_month' => Attendance::where('date', 'like', $thisMonth . '%')->count(),
            ],
            'permission' => [
                'total' => Permission::count(),
                'pending' => Permission::where('status', 'pending')->count(),
                'approved' => Permission::where('status', 'accepted')->count(),
                'rejected' => Permission::where('status', 'rejected')->count(),
                'this_month' => Permission::where('created_at', 'like', $thisMonth . '%')->count(),
            ]
        ];

        $recentAttendances = Attendance::with(['user.profile'])
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        $recentPermissions = Permission::with(['user.profile'])
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        return response()->json([
            'message' => 'Dashboard data berhasil diambil.',
            'data' => [
                'statistics' => $stats,
                'recent_attendances' => $recentAttendances,
                'recent_permissions' => $recentPermissions
            ]
        ], 200);
    }
}
