<?php

namespace App\Http\Controllers;

use App\Interfaces\ActionRoleRepositoryInterface;
use App\Interfaces\FormRepositoryInterface;
use App\Interfaces\RoleRepositoryInterface;
use App\Interfaces\StatusRepositoryInterface;
use App\Interfaces\TypeunitRepositoryInterface;
use App\Models\Action;
use App\Models\Status;
use Illuminate\Http\Request;
use PermissionHelper;
use Yajra\DataTables\Facades\DataTables;

class ChecklistController extends Controller
{
    protected $form;
    protected $typeUnit;
    protected $status;

    public function __construct(
        FormRepositoryInterface $form,
        TypeunitRepositoryInterface $typeUnit,
        StatusRepositoryInterface $StatusRepositoryInterface
    ) {
        $this->form = $form;
        $this->typeUnit = $typeUnit;
        $this->status = $StatusRepositoryInterface;
    }

    public function index()
    {
        $canCreate = PermissionHelper::hasPermission("checklist")->create;
        $typeUnit = $this->typeUnit->all();
        $form = $this->form->datatable();
        if (request()->ajax()) {
            return $this->datatable($form);
        }
        return view("checklist.index", compact("typeUnit", "canCreate"));
    }

    // api
    public function getByType($id)
    {
        $data = $this->form->findByUnit($id);
        return response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:40',
            'type_unit' => 'required',
        ]);

        $this->form->create([
            "title" => $request->title,
            "type_unit_id" => $request->type_unit,
            "note" => $request->note,
            "user_id" => auth()->user()->id
        ]);

        return response()->json(['message' => 'Data checklist berhasil ditambahkan.']);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $form = $this->form->find($id);
        $canCreate = PermissionHelper::hasPermission("checklist-sections")->create;
        $canUpdate = PermissionHelper::hasPermission("checklist-sections")->update;
        $canDelete = PermissionHelper::hasPermission("checklist-sections")->delete;
        $status = $this->status->all();

        return view("checklist.detail", compact("form", "canCreate", "canDelete", "canUpdate", "status"));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required|string|max:40',
            'type_unit' => 'required|string|max:20',
        ]);

        $this->form->update($id, [
            "title" => $request->title,
            "type_unit_id" => $request->type_unit,
            "note" => $request->note,
        ]);

        return response()->json(['message' => 'Data checklist berhasil diupdate.']);
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {

        $this->form->delete($id);
        return response()->json(data: ['message' => 'Data checklist berhasil dihapus.']);
    }

    public function datatable($data)
    {
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('title', function ($row) {
                $canEdit = PermissionHelper::hasPermission("checklist")->update;
                $url = route('checklist.show', $row->id);

                if ($canEdit) {
                    return '<a href="' . $url . '" class="text-primary fw-semibold">'
                        . e($row->title) .
                        '</a>';
                }

                return '<span>' . e($row->title) . '</span>';
            })
            ->addColumn('action', function ($row) {
                $canEdit = PermissionHelper::hasPermission("checklist")->update;
                $canDelete = PermissionHelper::hasPermission("checklist")->delete;

                if (!$canEdit && !$canDelete) {
                    return "<span class='text-muted fst-italic'>Only View</span>";
                }
                $actionBtn = "<div class='d-flex gap-2'>";

                $actionBtn .= '<a href="' . route("checklist.show", $row->id) . '"
                                data-id="' . $row->id . '"
                                class="detail btn btn-primary btn-sm"><i class="fa fa-eye"/></i></a>';

                $actionBtn .= request()->option == "active" ?
                    '<a href="javascript:void(0)"
                                data-id="' . $row->id . '"
                                data-title="' . $row->title . '"
                                data-note="' . $row->note . '"
                                data-type_unit="' . $row->type_unit_id . '"
                                class="edit btn btn-warning btn-sm"><i class="fa fa-pencil"></i></a>' : "";

                $actionBtn .= '<a href="javascript:void(0)"
                                data-id="' . $row->id . '"
                                class="delete btn btn-danger btn-sm"><i class="fa fa-trash"/></i></a>';

                $actionBtn .= "</div>";
                return $actionBtn;
            })
            ->addColumn("type_unit", function ($qr) {
                return $qr->typeUnit->name;
            })

            ->filterColumn('type_unit', function ($query, $keyword) {
                $query->whereHas('typeUnit', fn($q) => $q->where('name', 'like', "%{$keyword}%"));
            })
            ->orderColumn('type_unit', function ($query, $order) {
                $query->join('type_units', 'type_units.id', '=', 'forms.type_unit_id')
                    ->orderBy('type_units.name', $order);
            })
            ->rawColumns(['action', 'title'])
            ->make(true);
    }
}