<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Interfaces\SwpRepositoryInterface;
use Illuminate\Http\Request;
use PermissionHelper;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Yajra\DataTables\Facades\DataTables;

class SwpController extends Controller
{
    protected $swp;

    public function __construct(SwpRepositoryInterface $swp)
    {
        $this->swp = $swp;
    }

    public function index()
    {
        $canCreate = PermissionHelper::hasPermission("swp")->create;
        $option = request()->option;
        $swp = $this->swp->datatable();
        if (request()->ajax()) {
            return $this->datatable($swp);
        }
        return view("swp.index", compact("swp", "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([
            'title' => 'required|string|max:255',
            'file' => 'required|mimes:pdf|max:2048',
        ]);

        $swp = $this->swp->create([
            'title' => $validated['title'],
            'file' => '',
            'user_id' => auth()->id(),
        ]);


        if ($request->hasFile('file')) {
            $safeTitle = Str::slug($validated['title']);

            $filePath = $request->file('file')->storeAs(
                "SWP/{$swp->id}",
                "{$safeTitle}.pdf",
                'public'
            );

            $swp->update(['file' => $filePath]);
        }

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

    /**
     * Display the specified resource.
     */
    public function show(string $id) {
        $swp = $this->swp->find($id);
        if (!$swp->file || !Storage::disk('public')->exists($swp->file)) {
            abort(404, 'File tidak ditemukan');
        }
        $filePath = Storage::disk('public')->path($swp->file);
        return response()->file($filePath);
    }

    /**
     * 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)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'file' => 'nullable|mimes:pdf|max:2048',
        ]);

        $swp = $this->swp->find($id);

        $updateData = [
            'title' => $validated['title'],
            'user_id' => auth()->id(),
        ];

        if ($request->hasFile('file')) {
             if ($swp->file && Storage::disk('public')->exists($swp->file)) {
                Storage::disk('public')->delete($swp->file);
            }
            $safeTitle = Str::slug($validated['title']);
            $filePath = $request->file('file')->storeAs( "SWP/{$swp->id}", "{$safeTitle}.pdf", 'public' );
            $updateData['file'] = $filePath;
        }

        $swp->update($updateData);

        return response()->json(['message' => 'SWP berhasil diperbarui.']);
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id) {
        $swp = $this->swp->find($id);
        if (!empty($swp->file) && Storage::disk('public')->exists($swp->file)) {
            Storage::disk('public')->delete($swp->file);
        }
        $this->swp->delete($id);
        return response()->json(['message' => 'SWP berhasil dihapus.']); }

    public function datatable($data)
    {
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function ($row) {
                $canEdit = PermissionHelper::hasPermission("swp")->update;
                $canDelete = PermissionHelper::hasPermission("swp")->delete;
                $actionBtn = "<div class='d-flex gap-2'>";
                $actionBtn .= '<a href="' . route('swp.show', $row->id) . '"
                    target="_blank"
                    class="btn btn-info btn-sm">
                    <i class="fa fa-print"></i>
                </a>';
                $actionBtn .= $canEdit && request()->option == "active" ?
                    '<a href="javascript:void(0)"
                                data-id="' . $row->id . '"
                                data-title="' . $row->title . '"
                                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('user', function ($row) {
                if ($row->user_id == 1) {
                    return '-';
                }

                return $row->user->name ?? '-';
            })
            ->rawColumns(['action'])
            ->make(true);
    }
}