<?php

namespace App\Repositories\Admin;

use App\Models\User;
use App\Repositories\Interfaces\Admin\StaffInterface;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Traits\ImageTrait;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Hash;

class StaffRepository implements StaffInterface
{
    use ImageTrait;

    public function all()
    {
        return User::get();
    }

    public function store($request)
    {
        try {

            if (isset($request['image']) && $request['image'] instanceof UploadedFile) {
                $requestImage = $request['image'];
                $response = $this->saveImage($requestImage, '_staff_');
                $request['image'] = $response['images'];
            }

            $data = [
                'first_name' => $request['first_name'],
                'last_name' => $request['last_name'],
                'user_type' => 'staff',
                'phone' => $request['phone'],
                'gender' => $request['gender'],
                'email' => $request['email'],
                'password' => Hash::make($request['password']),
                'status' => $request['status'],
                'role_id' => 3,
                'image' => isset($request['image']) ? json_encode($request['image']) : '',
                'permissions' => $request['permissions'],
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            return User::create($data);

        } catch (\Exception $e) {
            return false;
        }
    }

    public function update($request, $id)
    {
        try {
            $user = User::where('id', $id)->first();

            if (isset($request['image']) && $request['image'] instanceof UploadedFile) {
                $requestImage = $request['image'];
                $this->imageDelete($id, 'user', 'image');
                $response = $this->saveImage($requestImage, '_staff_');
                $request['image'] = $response['images'];
            }

            $data = [
                'first_name' => $request['first_name'],
                'last_name' => $request['last_name'],
                'user_type' => 'staff',
                'phone' => $request['phone'],
                'gender' => $request['gender'],
                'email' => $request['email'],
                'password' => Hash::make($request['password']),
                'status' => $request['status'],
                'role_id' => 3,
                'image' => isset($request['image']) ? json_encode($request['image']) : $user->image,
                'permissions' => json_encode($request['permissions']),
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            return User::where('id', $id)->update($data);

        } catch (\Exception $e) {
            return false;
        }
    }
}
