<?php

namespace App\Repositories\Admin;

use App\Models\User;
use App\Repositories\Interfaces\Admin\SubscriberInterface;
use Carbon\Carbon;
use App\Traits\ImageTrait;
use Illuminate\Http\UploadedFile;

class SubscriberRepository implements SubscriberInterface
{
    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' => 'user',
                'phone' => $request['phone'],
                'gender' => $request['gender'],
                'email' => $request['email'],
                'password' => $request['password'],
                'status' => $request['status'],
                'image' => isset($request['image']) ? json_encode($request['image']) : '',
                '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'];
                $response = $this->saveImage($requestImage, '_staff_');
                $request['image'] = $response['images'];
            }

            $data = [
                'first_name' => $request['first_name'],
                'last_name' => $request['last_name'],
                'user_type' => 'user',
                'phone' => $request['phone'],
                'gender' => $request['gender'],
                'email' => $request['email'],
                'password' => $request['password'],
                'status' => $request['status'],
                'image' => isset($request['image']) ? json_encode($request['image']) : $user->image,
                'updated_at' => Carbon::now(),
            ];
            return User::where('id', $id)->update($data);
           
        } catch (\Exception $e) {
            return false;
        }
    }
}
