<?php
namespace App\Repositories\ApiRpositories;

use App\Interfaces\ApiInterface\MasterRepositoryInterface;
use App\Models\Form;
use App\Models\Unit;
use App\Models\User;
use PermissionHelper;

class MasterRepository implements MasterRepositoryInterface
{
    private $user;
    private $unit;
    private $form;

    public function __construct(User $user, Unit $unit, Form $form)
    {
        $this->user = $user;
        $this->unit = $unit;
        $this->form = $form;
    }

    public function getAllUser($search = null)
    {
        $allAccess = PermissionHelper::hasAllAccess();
        $role = auth()->user()->role;

        $query = $this->user
            ->select('id', 'name', 'email', 'role_id')
            ->when(!$allAccess, function ($rw) {
                $rw->where("location_id", auth()->user()->location_id);
            })
            ->with(['role'])
            ->when(auth()->user()->role_id != 1, function ($row) {
                $row->where("role_id", "<>", 1);
            })
            ->when($role->isAllLocation != "1" || $role->isAllLocation != 1 || $role->isAllLocation != true, function ($row) {
                $row->whereHas("role", function ($rw) {
                    $rw->where("isAllLocation", 0);
                    $rw->orWhereNull("isAllLocation");
                });
            });


        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'LIKE', "%{$search}%")
                    ->orWhere('email', 'LIKE', "%{$search}%");
            });
        }

        return $query->get()->map(function ($user) {
            return [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role->role,
            ];
        });
    }


    public function getAllUnit($search = null, $user = null)
    {
        $allAccess = PermissionHelper::hasAllAccess();

        $query = $this->unit
            ->select(
                'id',
                'unit_code',
                'unit_type',
                'production_year',
                'serial_number_unit',
                'serial_number_chassis',
                'hours_meter',
                'location_id',
                'type_id',
                'manufacture_id'
            )
            ->whereHas('location', function ($q) {
                $q->whereNull('deleted_at');
            })
            ->when(!$allAccess, function ($rw) {
                $rw->where("location_id", auth()->user()->location_id);
            })
            ->with(['location', 'unittype', 'manufacture']);

        // if ($user && $user->role_id !== 1) {
        //     $query->where('location_id', $user->location_id);
        // }

        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('unit_code', 'LIKE', "%{$search}%")
                    ->orWhere('unit_type', 'LIKE', "%{$search}%")
                    ->orWhere('production_year', 'LIKE', "%{$search}%")
                    ->orWhere('serial_number_unit', 'LIKE', "%{$search}%")
                    ->orWhere('serial_number_chassis', 'LIKE', "%{$search}%")
                    ->orWhere('hours_meter', 'LIKE', "%{$search}%");
            })
                ->orWhereHas('location', function ($q) use ($search) {
                    $q->where('name', 'LIKE', "%{$search}%");
                })
                ->orWhereHas('unittype', function ($q) use ($search) {
                    $q->where('name', 'LIKE', "%{$search}%");
                })
                ->orWhereHas('manufacture', function ($q) use ($search) {
                    $q->where('name', 'LIKE', "%{$search}%");
                });
        }

        return $query->FilterByRole()->get()->map(function ($unit) {
            return [
                'id' => $unit->id,
                'unit_code' => $unit->unit_code,
                'location' => $unit->location->name ?? "-",
                'type_unit' => $unit->unittype->name ?? "-",
                'manufacture' => $unit->manufacture->name ?? "-",
                'unit_type' => $unit->unit_type,
                'production_year' => $unit->production_year,
                'serial_number_unit' => $unit->serial_number_unit,
                'serial_number_chassis' => $unit->serial_number_chassis,
                'hours_meter' => $unit->hours_meter,
            ];
        });
    }


    public function getAllForm($search = null)
    {
        $allAccess = PermissionHelper::hasAllAccess();

        $query = $this->form->select(['id', 'title', 'note', 'type_unit_id'])
            ->when(!$allAccess, function ($rw) {
                $rw->where("site_id", auth()->user()->location_id);
            })
            ->with('typeUnit');

        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('title', 'LIKE', "%{$search}%");
            });
        }

        return $query->get()->map(function ($user) {
            return [
                'id' => $user->id,
                'title' => $user->title,
                'note' => $user->note,
                'typeunit' => $user->typeunit->name,
            ];
        });
    }

    public function getAllAproval($search = null)
    {
        $allAccess = PermissionHelper::hasAllAccess();
        $query = $this->user
            ->join('roles', 'users.role_id', '=', 'roles.id')
            ->when(!$allAccess, function ($rw) {
                $rw->where("site_id", auth()->user()->location_id);
            })
            ->select(
                'users.id',
                'users.name',
                'users.username',
                'users.email',
                'users.approve',
                'roles.role as role'
            );

        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('users.name', 'LIKE', "%{$search}%")
                    ->orWhere('users.email', 'LIKE', "%{$search}%")
                    ->orWhere('users.username', 'LIKE', "%{$search}%")
                    ->orWhere('roles.role', 'LIKE', "%{$search}%");
            });
        }

        $query->orderByRaw('CASE WHEN users.approve IS NULL THEN 0 ELSE 1 END ASC');

        return $query->get();
    }

    public function updateApproveStatus($id, $approve)
    {
        $user = User::find($id);

        if (!$user) {
            return null;
        }

        $user->approve = $approve;
        $user->save();

        return $user;
    }

}
