<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\FileManager;
use Validator;

class FilesManagerController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:file-manager-list', ['only' => ['index','store','list']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = FileManager::query();

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('name', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

            return view('file-manager.table', compact('data'));
        } else {
            $data = $data->paginate(10);

            return view('file-manager.index',compact('data'));
        }
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator =  Validator::make($request->all(),[
            'name' => 'required',
            'file' => 'required|mimes:jpeg,pdf,png,jpg,gif,svg,xlsx,docx|max:9000',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false,'message' => $validator->errors()->all()]);
        } else {

            if ($request->hasFile('file')) {
                $url      = \Str::slug($request->name);
                $path     = "upload/file/".$url.'/'.date('Y').'/'.date('m');
                $response = uploadImage($path, $request->file);

                if ($response['status'] == true)
                {
                    $image = $response['file_name'];
                }
                else
                {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
            }
            else
            {
                $image='';
            }

            $file = FileManager::create([
                    'name'           => $request->name,
                    'details'        => $request->details,
                    'file_type_id'   => $request->file_type_id,
                    'category_id'    => $request->category_id,
                    'file'           => $image,
                    'acl_permission' => '',
                    'status'         => 1,
                ]);

            if ($request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'File has been uploaded successfully',
                    'data'    => $file
                ]);
            }
        }
    }

    /**
     * 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)
    {
        $file = FileManager::find($id);

        if (!$file) {
            return response()->json([
                'success' => false,
                'message' => 'File not found!'
            ]);
        }

        return view('file-manager.edit', compact('file'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $file = FileManager::find($id);

        if (!$file) {
            return response()->json([
                'success' => false,
                'message' => 'File not found!'
            ]);
        }

        $validator =  Validator::make($request->all(),[
            'name' => 'required',
            'file' => 'mimes:jpeg,pdf,png,jpg,gif,svg,xlsx,docx|max:9000',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false,'message' => $validator->errors()->all()]);
        } else {

            if ($request->hasFile('file')) {
                $url      = \Str::slug($request->name);
                $path     = "upload/file/".$url.'/'.date('Y').'/'.date('m');
                $response = uploadImage($path, $request->file);

                if ($response['status'] == true)
                {
                    $image = $response['file_name'];

                    if (isset($file->file) && $file->file != '') {
                        deleteImage($file->file);
                    }
                }
                else
                {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
            }
            else
            {
                $image = $file->file;
            }

            $file->update([
                    'name'           => $request->name,
                    'details'        => $request->details,
                    'file_type_id'   => $request->file_type_id,
                    'category_id'    => $request->category_id,
                    'file'           => $image,
                    'acl_permission' => '',
                ]);

            if ($request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'File has been updated successfully',
                ]);
            }
        }
    }

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

        if (!$file) {
            return response()->json([
                'success' => false,
                'message' => 'File not found!'
            ]);
        }

        if (isset($file->file) && $file->file != '') {
            deleteImage($file->file);
        }

        $file->delete();

        return response()->json([
            'success' => true,
            'message' => 'File has been deleted successfully',
        ]);
    }

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

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['File status successfully change'],
                    'data'    => [
                       'redirect' => '/users/',
                       'reload'   => true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success' => false,
                   'message' => ['Error for change status'],
                ]);
            }
        }
    }
}
