<?php

namespace App\Http\Controllers;

use App\Interfaces\TypeunitRepositoryInterface;
use Illuminate\Http\Request;
use PermissionHelper;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Str;

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

    protected $type_unit;

    public function __construct(TypeunitRepositoryInterface $typeunitRepositoryInterface)
    {
        $this->type_unit = $typeunitRepositoryInterface;
    }
    public function index()
    {
        $data = $this->type_unit->all();
        $canCreate = PermissionHelper::hasPermission("unit-type")->create;

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

        return view('parts.unit_type.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)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $unitType = $this->type_unit->create([
            'name' => $request->name,
        ]);

        $folderPath = 'uploads/' . $unitType->id;
        if (!file_exists(public_path($folderPath))) {
            mkdir(public_path($folderPath), 0777, true);
        }

        $extension = $request->file('image')->getClientOriginalExtension();
        $fileName = Str::slug($request->name) . '.' . $extension;
        $request->file('image')->move(public_path($folderPath), $fileName);

        $unitType->update([
            'image' => $folderPath . '/' . $fileName,
        ]);

        $unitType->refresh();

        return response()->json([
            'success' => true,
            'message' => 'Data berhasil disimpan',
            'data' => $unitType
        ]);
    }


    /**
     * 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',
            'image' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
        ]);

        try {
            $unitType = $this->type_unit->find($id);

            if (!$unitType) {
                return redirect()->back()->with('error', 'Data tidak ditemukan.');
            }

            if ($request->hasFile('image')) {
                // Hapus gambar lama jika ada
                if ($unitType->image && file_exists(public_path($unitType->image))) {
                    unlink(public_path($unitType->image));
                }

                $folderPath = 'uploads/' . $unitType->id;
                if (!file_exists(public_path($folderPath))) {
                    mkdir(public_path($folderPath), 0777, true);
                }

                $extension = $request->file('image')->getClientOriginalExtension();
                $fileName = \Illuminate\Support\Str::slug($request->name) . '.' . $extension;

                $request->file('image')->move(public_path($folderPath), $fileName);
                $validated['image'] = $folderPath . '/' . $fileName;
            }

            $this->type_unit->update($id, $validated);

            return redirect()->back()->with('success', 'Data Tipe Unit berhasil diperbarui!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Gagal memperbarui data: ' . $e->getMessage());
        }
    }

    public function destroy(string $id)
    {
        try {
            $unitType = $this->type_unit->find($id);

            if (!$unitType) {
                return redirect()->back()->with('error', 'Data tidak ditemukan.');
            }

            // Hapus gambar jika ada
            if ($unitType->image && file_exists(public_path($unitType->image))) {
                unlink(public_path($unitType->image));
            }

            $folderPath = dirname(public_path($unitType->image));
            if (is_dir($folderPath) && count(scandir($folderPath)) <= 2) {
                rmdir($folderPath);
            }

            $this->type_unit->delete($id);

            return redirect()->back()->with('success', 'Data tipe unit berhasil dihapus!');
        } catch (\Illuminate\Database\QueryException $e) {
            if ($e->getCode() === '23000') {
                return redirect()->back()->with('error', 'Data tidak bisa dihapus karena sedang digunakan.');
            }

            return redirect()->back()->with('error', 'Terjadi kesalahan saat menghapus data.');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Gagal menghapus data: ' . $e->getMessage());
        }
    }


    public function datatable($data)
    {
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('image', function ($row) {
            if (!empty($row->image)) {
                $imagePath = public_path($row->image);
                $imageUrl = asset($row->image);

                if (file_exists($imagePath)) {
                    return '<img src="' . $imageUrl . '" 
                            alt="' . e($row->name) . '" 
                            width="60" height="60" 
                            style="object-fit: cover; border-radius: 8px; border: 1px solid #ddd;">';
                }

                return '<span class="text-warning fst-italic">File Missing</span>';
            }

            return '<span class="text-muted fst-italic">No Image</span>';
        })

            ->addColumn('action', function ($row) {
                $canEdit = PermissionHelper::hasPermission("unit-type")->update;
                $canDelete = PermissionHelper::hasPermission("unit-type")->delete;

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

                $buttons = '<div class="d-flex gap-2">';
                
                // Tombol edit
                if ($canEdit) {
                    $buttons .= '
                        <a href="javascript:void(0)" 
                        class="edit btn btn-warning btn-sm"
                        data-id="' . $row->id . '"
                        data-name="' . e($row->name) . '"
                        data-image="' . asset($row->image ?? '') . '">
                        <i class="fa fa-pencil"></i>
                        </a>';
                }

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

                $buttons .= '</div>';
                return $buttons;
            })
            ->rawColumns(['image', 'action'])
            ->make(true);
    }

}