<?php

namespace App\Http\Controllers;

use App\Interfaces\ManufactureRepositoryInterface;
use Illuminate\Http\Request;
use PermissionHelper;
use Yajra\DataTables\DataTables;
use Illuminate\Database\QueryException;

class ManufactureController extends Controller
{
    /**
     * Display a listing of the resource.
     */

    protected $manufactureRepository;

    public function __construct(ManufactureRepositoryInterface $manufacture)
    {
        $this->manufactureRepository = $manufacture;
    }

    public function index()
    {
        $data = $this->manufactureRepository->datatable();
        $canCreate = PermissionHelper::hasPermission("manufactures")->create;

        if (request()->ajax()) {
            return $this->datatable($data);
        }

        return view('parts.manufacture.index', ["canCreate" => $canCreate]);
    }

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

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

        try {
            $this->manufactureRepository->create($validated);

            return response()->json([
                'status' => 'success',
                'message' => 'Manufaktur berhasil ditambahkan.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Gagal menambahkan Manufaktur: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

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

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

        try {
            $this->manufactureRepository->update($id, $validated);

            return response()->json([
                'status' => 'success',
                'message' => 'Manufaktur berhasil diupdate.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Gagal mengupdate Manufaktur: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            $this->manufactureRepository->delete($id);

            return response()->json([
                'success' => true,
                'message' => 'Manufaktur berhasil dihapus!'
            ]);
        } catch (QueryException $e) {
            if ($e->getCode() == '23000') {
                return response()->json([
                    'success' => false,
                    'message' => 'Gagal menghapus manufaktur karena masih digunakan di data lain.'
                ], 400);
            }

            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat menghapus manufaktur.'
            ], 500);
        }
    }

    public function datatable($data)
    {
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function ($row) {
                $canEdit = PermissionHelper::hasPermission("manufactures")->update;
                $canDelete = PermissionHelper::hasPermission("manufactures")->delete;

                if (!$canEdit && !$canDelete) {
                    return "<span class='text-muted fst-italic'>Only View</span>";
                }
                
                $actionBtn = "<div class='d-flex gap-2'>";
                $actionBtn .= $canEdit ? '<a href="javascript:void(0)" class="edit btn btn-warning btn-sm" data-id="' . $row->id . '" data-name="' . $row->name . '"><i class="fa fa-pencil"></i></a> ' : "";
                $actionBtn .= $canDelete ? '<a href="javascript:void(0)" class="delete btn btn-danger btn-sm" data-id="' . $row->id . '"><i class="fa fa-trash"></i></a>' : "";
                $actionBtn .= "</div>";
                return $actionBtn;
            })

            ->rawColumns(['action'])
            ->make(true);
    }
}