<?php

namespace App\Repositories\Member;


use App\Models\Banner;

use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Carbon\Carbon;
use Storage;
use Image;

use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Imagick\Driver;


class BannerRepository
{
    public function getList($params)
    {
        $limit = @$params["limit"] ? (int) @$params["limit"] : 10;
        $sortColumn = @$params["sort"]["column"] ? $params["sort"]["column"] : "id";
        $sortDir = @$params["sort"]["dir"] ? $params["sort"]["dir"] : "desc";

        return Banner::when(@$params["is_active"], function($query){
            $query->where("is_active", true);
        })
        ->when(@$params['search'], function($query) use ($params) {
            $query->where('caption', 'ilike', '%' . $params['search'] . '%');
        })
        ->orderBy($sortColumn, $sortDir)
        ->paginate($limit);
    }

    public function create(array $data)
    {
        if(@$data['image']) {
            $path = $this->storeFile($data['image'], 'banner');
            $data['filename'] = $path;
        }

        $item = Banner::create($data);
        return $item;
    }

    public function update(Banner $item, array $data)
    {
        if(@$data['image']) {
            Storage::disk('public')->delete($item->filename);
            $path = $this->storeFile($data['image'], 'banner');
            $data['filename'] = $path;
        }
        $item->update($data);
        return $item;
    }

    public function delete(Banner $item)
    {
        Storage::disk('public')->delete($item->filename);
        $item->delete();
    }

    public function find($column, $value)
    {
        $item = Banner::where($column, $value)->firstOrFail();
        return $item;
    }

    public function storeFile($file, $dir)
    {
        $extension = $file->extension();
        $filename = '';

        while ($filename == '') {
            $random = bin2hex(openssl_random_pseudo_bytes(16)) . '.' . $extension;
            $exists = Storage::disk('public')->exists($dir . '/' . $random);
            if (!$exists) {
                $filename = $random;
            }
        }
        $file->storeAs($dir, $filename, "public");

        if (in_array($extension, ['jpg', 'jpeg', 'png'])) {
            $path = Storage::disk('public')->path($dir . '/' . $filename);

            $manager = new ImageManager(new Driver());
            $img = $manager->read($path);
            $img->scale(width: 900);
            $img->save($path);
        }

        return $dir . '/' . $filename;
    }
}
