<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\LateArrivalRequest;
use App\Services\LateArrivalService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class LateArrivalController extends Controller
{
    protected LateArrivalService $lateArrivalService;

    public function __construct(LateArrivalService $lateArrivalService)
    {
        $this->lateArrivalService = $lateArrivalService;
    }

    /**
     * Get user's late arrival requests
     */
    public function index(Request $request): JsonResponse
    {
        $user = Auth::user();
        $perPage = $request->input('per_page', 15);

        $requests = LateArrivalRequest::forUser($user->id)
            ->with(['attendance', 'approver'])
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);

        $data = $requests->map(function ($request) {
            return $this->formatRequest($request);
        });

        return response()->json([
            'success' => true,
            'data' => [
                'requests' => $data,
                'pagination' => [
                    'current_page' => $requests->currentPage(),
                    'last_page' => $requests->lastPage(),
                    'per_page' => $requests->perPage(),
                    'total' => $requests->total(),
                ],
            ],
        ]);
    }

    /**
     * Get late arrival status for today
     */
    public function status(): JsonResponse
    {
        $user = Auth::user();
        $status = $this->lateArrivalService->getStatus($user);

        return response()->json([
            'success' => true,
            'data' => $status,
        ]);
    }

    /**
     * Get reason types
     */
    public function getReasonTypes(): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => [
                'reason_types' => LateArrivalRequest::REASON_TYPES,
            ],
        ]);
    }

    /**
     * Create a new late arrival request
     */
    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'request_date' => 'required|date',
            'planned_arrival_time' => 'required|date_format:H:i',
            'reason_type' => 'required|string|in:' . implode(',', array_keys(LateArrivalRequest::REASON_TYPES)),
            'reason_detail' => 'nullable|string|max:500',
            'simulated_request_at' => 'nullable|date',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validasi gagal',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $lateArrivalRequest = $this->lateArrivalService->createRequest(
                $request->all(),
                Auth::user()
            );

            return response()->json([
                'success' => true,
                'message' => $lateArrivalRequest->is_auto_approved
                    ? 'Izin terlambat berhasil diproses'
                    : 'Pengajuan izin terlambat berhasil dikirim',
                'data' => [
                    'request' => $this->formatRequest($lateArrivalRequest),
                ],
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    /**
     * Get single request detail
     */
    public function show(LateArrivalRequest $lateArrival): JsonResponse
    {
        $user = Auth::user();

        // Check ownership
        if ($lateArrival->user_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak memiliki akses',
            ], 403);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'request' => $this->formatRequest($lateArrival->load(['attendance', 'approver'])),
            ],
        ]);
    }

    /**
     * Cancel a pending request
     */
    public function destroy(LateArrivalRequest $lateArrival): JsonResponse
    {
        $user = Auth::user();

        // Check ownership
        if ($lateArrival->user_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak memiliki akses',
            ], 403);
        }

        if (!$lateArrival->isPending()) {
            return response()->json([
                'success' => false,
                'message' => 'Pengajuan ini sudah diproses dan tidak dapat dibatalkan',
            ], 400);
        }

        $lateArrival->delete();

        return response()->json([
            'success' => true,
            'message' => 'Pengajuan berhasil dibatalkan',
        ]);
    }

    /**
     * Admin: Get pending requests
     */
    public function adminPending(Request $request): JsonResponse
    {
        $user = Auth::user();
        $company = $user->company;

        $requests = LateArrivalRequest::forCompany($company->id)
            ->pending()
            ->with(['user', 'attendance'])
            ->orderBy('created_at', 'desc')
            ->paginate($request->input('per_page', 15));

        $data = $requests->map(function ($request) {
            return $this->formatRequest($request);
        });

        return response()->json([
            'success' => true,
            'data' => [
                'requests' => $data,
                'pagination' => [
                    'current_page' => $requests->currentPage(),
                    'last_page' => $requests->lastPage(),
                    'total' => $requests->total(),
                ],
            ],
        ]);
    }

    /**
     * Admin: Approve a request
     */
    public function adminApprove(LateArrivalRequest $lateArrival): JsonResponse
    {
        $user = Auth::user();

        // Check company match
        if ($lateArrival->company_id !== $user->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak memiliki akses',
            ], 403);
        }

        try {
            $lateArrival = $this->lateArrivalService->approve($lateArrival, $user);

            return response()->json([
                'success' => true,
                'message' => 'Izin terlambat berhasil disetujui',
                'data' => [
                    'request' => $this->formatRequest($lateArrival),
                ],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    /**
     * Admin: Reject a request
     */
    public function adminReject(Request $request, LateArrivalRequest $lateArrival): JsonResponse
    {
        $user = Auth::user();

        // Check company match
        if ($lateArrival->company_id !== $user->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak memiliki akses',
            ], 403);
        }

        try {
            $lateArrival = $this->lateArrivalService->reject(
                $lateArrival,
                $user,
                $request->input('rejection_reason')
            );

            return response()->json([
                'success' => true,
                'message' => 'Izin terlambat berhasil ditolak',
                'data' => [
                    'request' => $this->formatRequest($lateArrival),
                ],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    /**
     * Format request for API response
     */
    protected function formatRequest(LateArrivalRequest $request): array
    {
        return [
            'id' => $request->id,
            'user_id' => $request->user_id,
            'user_name' => $request->user?->name,
            'attendance_id' => $request->attendance_id,
            'request_date' => $request->request_date->format('Y-m-d'),
            'request_date_formatted' => $request->request_date->translatedFormat('l, d F Y'),
            'planned_arrival_time' => $request->planned_arrival_time?->format('H:i'),
            'reason_type' => $request->reason_type,
            'reason_type_label' => $request->reason_type_label,
            'reason_detail' => $request->reason_detail,
            'full_reason' => $request->full_reason,
            'status' => $request->status,
            'status_label' => $request->status_label,
            'is_auto_approved' => $request->is_auto_approved,
            'approver_name' => $request->approver?->name,
            'approved_at' => $request->approved_at?->toIso8601String(),
            'approved_at_formatted' => $request->approved_at?->translatedFormat('d M Y H:i'),
            'rejection_reason' => $request->rejection_reason,
            'actual_checkin_at' => $request->actual_checkin_at?->toIso8601String(),
            'created_at' => $request->created_at->toIso8601String(),
            'created_at_formatted' => $request->created_at->translatedFormat('d M Y H:i'),
        ];
    }
}
