<?php

namespace App\Http\Controllers\APIManagement;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\StorageSetting;
use Illuminate\Support\Facades\Session;

class StorageSettingsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:storage-settings-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->modulePermissionCheck('STORAGE_SETTINGS')) {
            abort(404);
        }

        $data = StorageSetting::paginate(10);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');
            $data         = StorageSetting::when(!empty($search_query), function ($query) use ($search_query) {
                                    return $query->where('storage_max_upload_size', 'like', '%'.$search_query.'%')
                                    ->orWhere('storage_validation', 'like', '%'.$search_query.'%')
                                    ->orWhere('storage_type', 'like', '%'.$search_query.'%');
                            })
                            ->paginate($sort_by);

            return view('storage-settings.table', compact('data'));
        }else{
            return view('storage-settings.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('storage-settings.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = $request->validate([
            'storage_type'            => 'required',
            'bucket_name'             => 'required',
            'storage_max_upload_size' => 'required',
            'storage_validation'      => 'required',
            'main_folder'             => 'required',
            'storage_limit'           => 'required',
            'acl'                     => 'required',
            'region'                  => 'required',
            'access_key'              => ($request->input('storage_type') !== 'local') ? 'required' : '',
            'secret_key'              => ($request->input('storage_type') !== 'local') ? 'required' : '',
        ]);

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $data['storage_validation'] = implode(',',$request->storage_validation);

        $data['bucket_code'] = strtoupper(str_replace(' ', '_', $request->bucket_name));

        $data_store = StorageSetting::create($data);
        $session = $this->setStorageSettingSession();

        return redirect()->route('storage-settings.index')
            ->with('success', 'Storage settings created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = StorageSetting::find($id);

        return view('storage-settings.edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->except([
            '_token',
            '_method',
        ]);

        $validator = $request->validate([
            'storage_type'            => 'required',
            'storage_max_upload_size' => 'required',
            'storage_validation'      => 'required',
            'main_folder'             => 'required',
            'storage_limit'           => 'required',
            'access_key'              => ($request->input('storage_type') !== 'local') ? 'required' : '',
            'secret_key'              => ($request->input('storage_type') !== 'local') ? 'required' : '',
            'acl'                     => ($request->input('storage_type') !== 'local') ? 'required' : '',
        ]);

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $data['storage_validation'] = implode(',',$request->storage_validation);

        $data_update = StorageSetting::where('id', $id)->update($data);
        $session     = $this->setStorageSettingSession();

        return redirect()->route('storage-settings.index')
            ->with('success', 'Storage settings updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        StorageSetting::find($request->id)->delete();

        $Redirect = 'storage-settings';
        $session = $this->setStorageSettingSession();
        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
       if ($request->ajax())
       {
           $data = array('status' => $request->status );
           $Update = StorageSetting::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Storage setting status successfully change'],
                   'data'=>[
                       'redirect'=>'/buckets/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{

               return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
    }
    public function setStorageSettingSession()
    {
        $BucketData = StorageSetting::select([
            'main_folder',
            'access_key',
            'secret_key',
            'region',
            'bucket_name',
            'storage_validation',
            'storage_max_upload_size',
        ])
        ->where(['status' => '1', 'storage_type' => 's3_bucket'])->first();

        Session::put('BucketData', $BucketData);
    }
}
