<?php
namespace App\Repositories;

use App\Interfaces\DailyRepositoryInterface;
use App\Interfaces\StbmRepositoryInterface;
use App\Interfaces\UserRepositoryInterface;
use App\Models\UserRoles;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use PermissionHelper;

class UserRepository implements UserRepositoryInterface
{
    protected $model;
    protected $daily;
    protected $stbm;

    public function __construct(User $user, DailyRepositoryInterface $di, StbmRepositoryInterface $si)
    {
        $this->model = $user;
        $this->daily = $di;
        $this->stbm = $si;
    }

    public function all()
    {
        $isAdmin = PermissionHelper::hasAllAccess();
        $role = auth()->user()->role;
        return $this->model->where('approve', 1)->orderBy("id", "Desc")
            ->whereHas("role", function ($q) {
                $q->whereNull("deleted_at"); // hanya user yang role-nya aktif
            })
            ->whereHas("location", function ($q) {
                $q->whereNull("deleted_at"); // hanya user yang location-nya aktif
            })->when(!$isAdmin, function ($row) {
                $row->where("location_id", auth()->user()->location_id);
            })
            ->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");
                });
            })
            ->get();
    }

    public function datatable()
    {
        $isAdmin = PermissionHelper::hasAllAccess();
        $role = auth()->user()->role;

        $query = $this->model->where('approve', 1)
            ->when(empty(request('order')) || (request('order')[0]['name'] ?? 'DT_RowIndex') === 'DT_RowIndex', fn($q) => $q->orderBy('users.id', 'desc'))
            ->whereHas("role", function ($q) {
                $q->whereNull("deleted_at"); // hanya user yang role-nya aktif
            })
            ->whereHas("location", function ($q) {
                $q->whereNull("deleted_at"); // hanya user yang location-nya aktif
            })
            ->when(!$isAdmin, function ($row) {
                $row->where("location_id", auth()->user()->location_id);
            })
            ->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");
                });
            })
        ;

        return $query;
    }

    public function datatableApprove()
    {
        $role = auth()->user()->role;

        $isAdmin = PermissionHelper::hasAllAccess();
        return $this->model
            ->where(function ($query) {
                $query->where('approve', 0)
                    ->orWhereNull('approve');
            })
            ->when(!$isAdmin, function ($row) {
                $row->where("location_id", auth()->user()->location_id);
            })
            ->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");
                });
            })
            ->orderByRaw('approve IS NOT NULL')
            ->when(empty(request('order')) || (request('order')[0]['name'] ?? 'DT_RowIndex') === 'DT_RowIndex', fn($q) => $q->orderBy('users.id', 'desc'))
            // ->orderBy('id', 'desc')
        ;
    }

    public function datatableTrash()
    {
        $user = auth()->user();
        $role = auth()->user()->role;

        $query = $this->model
            ->onlyTrashed()
            ->when(empty(request('order')) || (request('order')[0]['name'] ?? 'DT_RowIndex') === 'DT_RowIndex', fn($q) => $q->orderBy('users.id', 'desc'))
            // ->orderBy("id", "desc")
            ->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 (!PermissionHelper::hasAllAccess()) {
            $query->where("location_id", $user->location_id);
        }

        return $query;
    }


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

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


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

    public function delete($id)
    {
        $option = request()->option;
        $user = $this->model->withTrashed()->findOrFail($id);

        if ($option == "delete") {
            return $user->delete();
        }

        if ($option == "restore") {
            return $user->restore();
        }

        if ($option == "force-delete") {
            DB::beginTransaction();

            try {
                if (DB::table('forms')->where('user_id', $user->id)->exists()) {
                    DB::table('forms')->where('user_id', $user->id)->delete();
                }

                if (DB::table('swp')->where('user_id', $user->id)->exists()) {
                    DB::table('swp')->where('user_id', $user->id)->delete();
                }

                $dailies = DB::table('dailies')->where('user_id', $user->id)->get();
                $stbm = DB::table('stbm')->where('user_id', $user->id)->get();

                foreach ($dailies as $d) {
                    $this->daily->delete($d->id);
                }
                foreach ($stbm as $d) {
                    $this->stbm->delete($d->id);
                }

                // if ($dailies->count() > 0) {
                //     $basePath = public_path('PDF_PMM');

                //     foreach ($dailies as $daily) {
                //         DB::table('detail_dailies')->where('dailies_id', $daily->id)->delete();

                //         $pattern = $basePath . DIRECTORY_SEPARATOR . '*' . DIRECTORY_SEPARATOR . '*' . DIRECTORY_SEPARATOR . '*' . DIRECTORY_SEPARATOR . '*' . $daily->code_report . '*.pdf';
                //         $files = glob($pattern);

                //         if (!empty($files)) {
                //             foreach ($files as $file) {
                //                 if (file_exists($file)) {
                //                     unlink($file); // hapus file PDF
                //                 }
                //             }
                //         }
                //     }

                //     DB::table('dailies')->where('user_id', $user->id)->delete();
                // }

                // if ($stbm->count() > 0) {

                //     foreach ($stbm as $s) {
                //         DB::table('stbm_image')->where('stbm_id', $s->id)->delete();
                //         DB::table('stbm_participant')->where('stbm_id', $s->id)->delete();
                //     }

                //     DB::table('stbm')->where('user_id', $user->id)->delete();
                // }

                DB::table('users')->where('id', $user->id)->delete();

                DB::commit();
                return true;
            } catch (\Exception $e) {
                DB::rollBack();
                throw $e;
            }
        }

        return false;
    }

}
