<?php
namespace App\Repositories;

use App\Interfaces\StbmRepositoryInterface;
use App\Models\Stbm;
use App\Models\Stbm_Image;
use App\Models\Stbm_Participant;
use PermissionHelper;

class StbmRepository implements StbmRepositoryInterface
{
    private $action;
    private $stbmParticipant;
    private $stbmImage;

    public function __construct(Stbm $action, Stbm_Image $stbmImage, Stbm_Participant $stbmParticipant)
    {
        $this->action = $action;
        $this->stbmParticipant = $stbmParticipant;
        $this->stbmImage = $stbmImage;
    }

    public function all()
    {
        $isAdmin = PermissionHelper::hasAllAccess();
        $query = $this->action->orderBy("id", "desc")->with(["location", "images", "participant", "user"]);

        if (!$isAdmin) {
            $query->where("location_id", auth()->user()->location_id);
        }

        $isSO = strtolower(auth()->user()->role->role) == "so";

        if ($isSO) {
            $query->where("user_id", auth()->user()->user_id);
        }

        return $query->get();
    }
    public function datatable()
    {
        $isAdmin = PermissionHelper::hasAllAccess();
        $query = $this->action
            // ->orderBy("id", "desc")
            ->when(empty(request('order')) || (request('order')[0]['name'] ?? 'DT_RowIndex') === 'DT_RowIndex', fn($q) => $q->orderBy('stbm.id', 'desc'))
            ->with(["location", "images", "participant", "user"]);

        if (!$isAdmin) {
            $query->where("location_id", auth()->user()->location_id);
        }

        $isSO = strtolower(auth()->user()->role->role) == "so";
        if ($isSO) {
            $query->where("user_id", auth()->user()->user_id);
        }

        return $query;
    }

    public function find($id)
    {
        return $this->action->with(["location", "images", "participant", "user"])->findOrFail($id);
    }

    public function create(array $data)
    {
        $data["user_id"] = auth()->user()->id;
        $result = $this->action->create($data);


        if (request()->hasFile('images')) {
            foreach (request()->file('images') as $image) {
                $filename = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();

                // $destinationPath = public_path("STBM/{$result->id}");
                // if (!file_exists($destinationPath)) {
                //     mkdir($destinationPath, 0777, true);
                // }

                // $image->move($destinationPath, $filename);

                // // Simpan path relatif untuk database (opsional)
                // $path = "STBM/{$result->id}/{$filename}";

                $path = $image->storeAs(
                    "STBM/{$result->id}",
                    $filename,
                    'public'
                );

                // Simpan path ke database
                $this->stbmImage->create([
                    "stbm_id" => $result->id,
                    "image" => $path
                ]);
            }
        }



        foreach ($data["participant"] as $part) {
            if (empty($part))
                continue;
            $this->stbmParticipant->create([
                "stbm_id" => $result->id,
                "name" => $part
            ]);
        }

        return $result;
    }

    public function update($id, array $data, $fromApi = false)
    {
        $stbm = $this->action->findOrFail($id);
        $data["user_id"] = auth()->user()->id;

        $stbm->update($data);

        if ($fromApi) {
            foreach ($stbm->images as $img) {
                $filePath = public_path($img->image);

                if ($img) {
                    \Storage::disk('public')->delete($img->image);
                    $img->delete();
                }
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
                $img->delete();
            }
        }
        if (request()->hasFile('images')) {
            foreach (request()->file('images') as $image) {
                $filename = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();

                // $destinationPath = public_path("STBM/{$stbm->id}");
                // if (!file_exists($destinationPath)) {
                //     mkdir($destinationPath, 0777, true);
                // }

                // $image->move($destinationPath, $filename);

                // // Simpan path relatif untuk database (opsional)
                // $path = "STBM/{$stbm->id}/{$filename}";

                $path = $image->storeAs(
                    "STBM/{$stbm->id}",
                    $filename,
                    'public'
                );
                $this->stbmImage->create([
                    "stbm_id" => $stbm->id,
                    "image" => $path
                ]);
            }
        }

        if (!empty($data['deleted_images'])) {
            foreach ($data['deleted_images'] as $imageId) {
                $image = $this->stbmImage->find($imageId);
                $filePath = public_path($image->image);

                if ($image) {
                    \Storage::disk('public')->delete($image->image);
                    $image->delete();
                }
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
                $image->delete();
            }
        }

        $this->stbmParticipant->where('stbm_id', $stbm->id)->delete();

        if (!empty($data["participant"])) {
            foreach ($data["participant"] as $part) {
                if (empty($part))
                    continue;
                $this->stbmParticipant->create([
                    "stbm_id" => $stbm->id,
                    "name" => $part
                ]);
            }
        }

        return $stbm;
    }


    public function delete($id)
    {
        $stbm = $this->find($id);

        if (!$stbm) {
            return false;
        }
        foreach ($stbm->images as $image) {
            $filePath = public_path($image->image);
            if ($image) {
                \Storage::disk('public')->delete($image->image);
                $image->delete();
            }
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        $this->stbmParticipant->where('stbm_id', $stbm->id)->delete();
        return $stbm->delete();
    }

}
