<?php
namespace App\Repositories;

use App\Interfaces\DailyRepositoryInterface;
use App\Interfaces\FormRepositoryInterface;
use App\Interfaces\StatusRepositoryInterface;
use App\Models\Daily;
use App\Models\Form;
use App\Models\FormItem;
use App\Models\FormSection;
use App\Models\Role;
use App\Models\Status;
use PermissionHelper;

class FormRepository implements FormRepositoryInterface
{
    private $form;
    private $formSect;
    private $formItem;
    private $daily;

    public function __construct(Form $form, FormSection $formSect, FormItem $formItem, DailyRepositoryInterface $daily)
    {
        $this->form = $form;
        $this->formSect = $formSect;
        $this->formItem = $formItem;
        $this->daily = $daily;
    }

    public function all()
    {
        $isAdmin = PermissionHelper::hasAllAccess();

        $query = $this->form
            ->with(['typeUnit', 'typeUnit.units.location'])
            ->orderBy("id", "desc");

        if (!$isAdmin) {
            $query->whereHas('typeUnit.units.location', function ($q) {
                $q->where('id', auth()->user()->location_id);
            });
        }

        return $query->FilterByRole()->get();

    }

    public function datatable()
    {
        $isAdmin = PermissionHelper::hasAllAccess();

        $order = request('order');
        \Log::info('Order parameter:', ['order' => $order]);

        $query = $this->form
            ->with(['typeUnit', 'typeUnit.units.location'])
            ->when(empty(request('order')) || (request('order')[0]['name'] ?? 'DT_RowIndex') === 'DT_RowIndex', function ($q) {
                \Log::info('Default orderBy dijalankan');
                $q->orderBy('forms.id', 'desc');
            });

        if (!$isAdmin) {
            $query->whereHas('typeUnit.units.location', function ($q) {
                $q->where('id', auth()->user()->location_id);
            });
        }

        return $query->FilterByRole();
    }



    public function find($id)
    {
        return $this->form->findOrFail($id);
    }

    public function findByUnit($id)
    {
        return $this->form->where('type_unit_id', $id)->get();
    }

    public function create(array $data)
    {
        return $this->form->create($data);
    }

    public function update($id, array $data)
    {
        $location = $this->find($id);
        $location->update($data);
        return $location;
    }

    public function delete($id)
    {

        $daily = Daily::where("form_id", $id)->get();
        foreach ($daily as $d) {
            $this->daily->delete($d->id);
        }

        // $this->formSect->where("form_id", $id)->delete();
        $form = $this->form->find($id);
        foreach ($form->sections as $sect) {
            $sect->items()->delete();
            $sect->delete();
        }

        return $form->delete();

    }
}
