<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Interfaces\ApiInterface\ChecklistRepositoryInterface;
use App\Models\Daily;
use App\Models\Location;
use App\Models\Shift;
use App\Repositories\ApiRepositories\FormRepository;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;


class CheckListController extends Controller
{
    protected $formRepository;

    public function __construct(ChecklistRepositoryInterface $formRepository)
    {
        $this->formRepository = $formRepository;
    }

    public function getAllChecklist()
    {
        $data = $this->formRepository->getFormsWithUncheckedUnits();

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

    public function getAllShift()
    {
        $data = $this->formRepository->getShift();

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

    public function getUnitByForm(Request $request, $id)
    {
        $user = Auth::guard('sanctum')->user();

        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unauthorized',
            ], 401);
        }

        $locationId = $user->role->isAllLocation == 0 ? $user->location_id : null;

        $data = $this->formRepository->getUnit($id, $locationId);

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

    public function getQuestion($id, Request $request)
    {
        $unitId = $request->query('unit');
        $shiftId = $request->query('shift');
        try {
            $data = $this->formRepository->getFormDetail($id, $unitId, $shiftId);
            return response()->json([
                'status' => 'success',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Gagal mengambil data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function getHistory(Request $request)
    {
        try {
            $user = Auth::guard('sanctum')->user();
            $shiftId = request()->query("shift");
            $sitesId = request()->query("site");
            $date = request()->query("date");
            $search = request()->query("search");

            if (!$user) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Unauthorized',
                ], 401);
            }

            $isAdmin = $user->role_id == 1 ? true : false;

            $data = $this->formRepository->getHistory($user->id, $isAdmin, $shiftId, $sitesId, $date,$search);

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

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Gagal mengambil data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'form_id' => 'required|exists:forms,id',
            'user_id' => 'required|exists:users,id',
            'shift_id' => 'required|exists:shifts,id',
            'location_id' => 'required',
            'unit_id' => 'required',
            'status_daily' => 'nullable|in:pending,completed',
            'details' => 'required|array|min:1',
            'details.*.unit_id' => 'required|exists:units,id',
            'details.*.form_item_id' => 'required|exists:form_items,id',
            'details.*.status_id' => 'required|exists:status,id',
            'details.*.note' => 'nullable|string',
            'comment' => 'nullable|string'
        ]);

        try {
            $daily = $this->formRepository->createDailyWithDetails($validated);

            return response()->json([
                'success' => true,
                'message' => 'Daily report berhasil disimpan dan PDF dibuat (jika tidak error).',
                'data' => $daily,
            ], 201);

        } catch (\Throwable $e) {
            Log::error("❌ Gagal menyimpan Daily Report: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal menyimpan daily report: ' . $e->getMessage(),
            ], 500);
        }
    }


    public function pdf($id)
    {
        try {
            $daily = Daily::where('id', $id)->firstOrFail();
            $year = \Carbon\Carbon::parse($daily->date)->format('Y');
            $month = \Carbon\Carbon::parse($daily->date)->format('m');
            $fileName = "{$daily->code_report}.pdf";
            $shift = Shift::find($daily->shift_id);
            $locationName = str_replace(" ", "_", $daily->location->name);
            $relativePath = "PDF_PMM/{$year}/{$month}/{$locationName}/{$shift->name}/{$fileName}";
            $filePath = public_path($relativePath);

            if (!File::exists($filePath)) {
                return response()->json([
                    'status' => false,
                    'message' => 'File PDF tidak ditemukan di folder public.'
                ]);
            }

            $fileUrl = asset($relativePath);

            return response()->json([
                'status' => true,
                'message' => 'File PDF ditemukan.',
                'file' => $fileUrl
            ]);

        } catch (\Throwable $th) {
            return response()->json([
                'status' => false,
                'message' => 'Gagal download PDF: ' . $th->getMessage(),
            ]);
        }
    }

    public function getDailyStatus(Request $request)
    {
        $tanggal = $request->query('tanggal') ?? now()->toDateString();
        $locationId = $request->query('location_id');

        if (!$locationId) {
            return response()->json([
                'message' => 'Parameter location_id wajib diisi.'
            ], 400);
        }

        $site = Location::with(['units.unittype'])
            ->where('id', $locationId)
            ->first();

        if (!$site) {
            return response()->json([
                'message' => 'Location tidak ditemukan.'
            ], 404);
        }

        $dailyList = Daily::with(['shift', 'unit', 'detail'])
            ->whereDate('date', $tanggal)
            ->whereHas('unit', function ($query) use ($locationId) {
                $query->where('location_id', $locationId);
            })
            ->get()
            ->map(function ($daily) {
                $details = $daily->detail;
                $total = $details->count();

                if ($total === 0) {
                    $daily->status_checklist = 'Belum Checklist';
                    return $daily;
                }

                $totalScore = $details->sum(function ($d) {
                    switch ($d->status_id) {
                        case 1: return 4;
                        case 2: return 3;
                        case 3: return 2;
                        case 4: return 1;
                        default: return 0;
                    }
                });

                $persen = ($totalScore / ($total * 4)) * 100;

                $daily->status_checklist = match (true) {
                    $persen >= 80 => 'Baik',
                    $persen >= 50 => 'Cukup',
                    $persen >= 30 => 'Rusak',
                    default => 'Rusak Fatal',
                };

                return $daily;
            });

        $groupedDaily = $dailyList->groupBy(function ($item) {
            return $item->unit->id . "_" . $item->shift_id;
        })->map(fn($rows) => $rows->first());

        $colorMap = [
            'Baik' => '#007bff',
            'Cukup' => '#fd7e14',
            'Rusak' => '#DD0303',
            'Rusak Fatal' => '#6c757d',
            'Belum Checklist' => '',
            'N/A' => '#6c757d',
        ];

        $response = [
            'site_id' => $site->id,
            'site_name' => $site->name,
            'shifts' => $site->shift->map(function ($shift) use ($site, $groupedDaily, $colorMap) {
                $units = $site->units
                    ->sortBy(function ($item) {
                        if (Str::startsWith($item->unit_code, 'L-')) return 1;
                        if (Str::startsWith($item->unit_code, 'E-')) return 2;
                        if (Str::startsWith($item->unit_code, 'DT-')) return 3;
                        if (Str::startsWith($item->unit_code, 'S-')) return 4;
                        return 5;
                    })
                    ->map(function ($item) use ($shift, $groupedDaily, $colorMap) {
                        $key = $item->id . "_" . $shift->id;
                        $status = $groupedDaily[$key]->status_checklist ?? 'Belum Checklist';

                        return [
                            'unit_id' => (string)$item->id,
                            'unit_code' => $item->unit_code,
                            'status_checklist' => $status,
                            'color' => $colorMap[$status] ?? '',
                            'image' => $item->unittype->image ? asset($item->unittype->image) : asset('images/default-icon.png'),
                        ];
                    });

                return [
                    'shift_id' => $shift->id,
                    'shift_name' => $shift->name,
                    'units' => $units->values(),
                ];
            }),
        ];

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


    public function deleteHistory($id)
    {
        $this->formRepository->deleteDailyWithDetails($id);

        return response()->json([
            'status' => 'success',
            'message' => 'data berhasil dihapus'
        ]);
    }
}