<?php

namespace App\Http\Controllers;

use App\Interfaces\LocationRepositoryInterface;
use App\Interfaces\StbmRepositoryInterface;
use App\Models\Stbm;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use PermissionHelper;
use Yajra\DataTables\Facades\DataTables;

class StbmController extends Controller
{

    protected $stbm;
    protected $location;
    public function __construct(StbmRepositoryInterface $stbm, LocationRepositoryInterface $locationRepository)
    {
        $this->stbm = $stbm;
        $this->location = $locationRepository;
    }
    public function index()
    {
        $canCreate = PermissionHelper::hasPermission("stbm")->create;
        $stbm = $this->stbm->datatable();
        $location = $this->location->all();
        // dd($stbm->get()[0]->images);
        if (request()->ajax()) {
            return $this->datatable($stbm);
        }
        return view("stbm.index", compact("stbm", "canCreate", "location"));
    }

    public function store(Request $request)
    {
        $validated = Validator::make($request->all(), [
            'name' => 'required|string|max:100',
            'location_id' => 'required|integer|exists:locations,id',
            'date' => 'required|date',
            'topic' => 'required|string|max:255',
            'description' => 'required|string',
            // "images" => "required",
            'images.*' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'participant' => 'nullable|array',
            'participant.*' => 'nullable|string|max:100',
        ])->after(function ($validator) use ($request) {
            $participants = collect($request->participant)
                ->filter(fn($p) => !empty(trim($p))); // ambil yg tidak kosong
            $images = $request->hasFile("images");
            ; // ambil yg tidak kosong

            if ($participants->count() < 1) {
                $validator->errors()->add('participant[0]', 'Minimal 1 peserta harus diisi.');
            }
            if (!$images) {
                $validator->errors()->add('images[0]', 'Minimal 1 dokumentasi harus diisi.');
            }
        })->validate();

        try {

            $this->stbm->create(request()->all());
            return response()->json(["message" => "Stbm berhasil diubah"], 200);
        } catch (\Throwable $th) {
            return response()->json(["message" => "Stbm gagal diubah"], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        try {
            $stbm = $this->stbm->find($id);
            return response()->json($stbm, 200);
        } catch (\Throwable $th) {
            return response()->json(["message" => "Terjadi kesalahan dengan server"], 500);
        }
    }
    public function donwloadPdf($id)
    {
        try {
            $stbm = $this->stbm->find($id);
            $pdf = Pdf::loadView('stbm.pdf', [
                "stbm" => $stbm
            ])->setPaper('a4', 'portrait');

            $fileName = "TBM_"
                . Carbon::parse($stbm->date)->format('dmY') . "_"
                . $stbm->location->name . "_"
                . $stbm->user->name;

            return $pdf->stream($fileName, [
                'Content-Type' => 'application/pdf',
            ]);

        } catch (Exception $e) {
            return response()->json(['message' => 'Data laporan ini kosong atau tidak ada checklist'], 404);
        }
    }


    public function update(Request $request, $id)
    {
        $validated = Validator::make($request->all(), [
            'name' => 'required|string|max:100',
            'location_id' => 'required|integer|exists:locations,id',
            'date' => 'required|date',
            'topic' => 'required|string|max:255',
            'description' => 'required|string',
            'images.*' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'participant' => 'nullable|array',
            'participant.*' => 'nullable|string|max:100',
        ])->after(function ($validator) use ($request) {
            $participants = collect($request->participant)
                ->filter(fn($p) => !empty(trim($p))); // ambil yg tidak kosong
            $images = $request->hasFile("images") || count($request->old_images ?? []) > 0;
            ; // ambil yg tidak kosong

            if ($participants->count() < 1) {
                $validator->errors()->add('participant[0]', 'Minimal 1 peserta harus diisi.');
            }
            if (!$images) {
                $validator->errors()->add('images[0]', 'Minimal 1 dokumentasi harus diisi.');
            }
        })->validate();


        try {

            $this->stbm->update($id, request()->all());
            return response()->json(["message" => "Stbm berhasil diubah", request()->all()], 200);
        } catch (\Throwable $th) {
            return response()->json(["message" => "Stbm gagal diubah", request()->all(), request()->file('images')], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $this->stbm->delete($id);
            return response()->json(["message" => "Stbm berhasil dihapus"], 200);
        } catch (\Throwable $th) {
            return response()->json(["message" => "Stbm gagal dihapus"], 500);
        }
    }


    public function datatable($data)
    {
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function ($row) {
                $canEdit = PermissionHelper::hasPermission("stbm")->update;
                $canDelete = PermissionHelper::hasPermission("stbm")->delete;
                $canRead = PermissionHelper::hasPermission("stbm")->read;
                $actionBtn = "<div class='d-flex gap-2'>";
                $actionBtn .= $canRead ?
                    '<a href="' . route("stbm.pdf", $row->id) . '"
                                data-id="' . $row->id . '"
                                target="_blank"
                                class=" btn btn-primary btn-sm"><i class="fa fa-print"></i></a>' : "";
                $actionBtn .= $canEdit ?
                    '<a href="javascript:void(0)"
                                data-id="' . $row->id . '"
                                data-name="' . ($row->user->name ?? "-") . '"
                                class="edit btn btn-warning btn-sm"><i class="fa fa-pencil"></i></a>' : "";
                $actionBtn .= $canDelete ? '<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("location", function ($row) {
                return $row->location->name ?? "-";
            })
            ->addColumn("name", function ($row) {
                return $row->user->name ?? "-";
            })
            ->addColumn("description", function ($row) {
                return $row->description;
            })
            ->filterColumn('location', function ($query, $keyword) {
                $query->whereHas('location', fn($q) => $q->where('name', 'like', "%{$keyword}%"));
            })
            ->orderColumn('location', function ($query, $order) {
                $query->join('locations', 'locations.id', '=', 'stbm.location_id')
                    ->orderBy('locations.name', $order);
            })
            ->filterColumn('name', function ($query, $keyword) {
                $query->whereHas('user', fn($q) => $q->where('name', 'like', "%{$keyword}%"));
            })
            ->orderColumn('name', function ($query, $order) {
                $query->join('users', 'users.id', '=', 'stbm.user_id')
                    ->orderBy('users.name', $order);
            })
            // ->filter(function ($query) {
            //     if ($search = request()->get('search')['value']) {
            //         $query->where(function ($q) use ($search) {
            //             $q->orWhereHas('location', function ($q2) use ($search) {
            //                 $q2->where('name', 'like', "%{$search}%");
            //             });
            //             $q->orWhereHas('user', function ($q2) use ($search) {
            //                 $q2->where('name', 'like', "%{$search}%");
            //             });
            //         });
            //         $query->orWhere("topic", "like", "%{$search}%");
            //         $query->orWhere("description", "like", "%{$search}%");
            //     }
            // })
            ->rawColumns(['action', "description"])
            ->make(true);
    }
}
