<?php

namespace App\Http\Controllers;

use App\DataFile;
use Illuminate\Http\Request;
use App\Http\Requests\ValidationRequest;
use Helper;
use Carbon\Carbon;
use File;
use Image;
use Alert;
use Illuminate\Database\QueryException;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Yajra\DataTables\Facades\DataTables;

class FileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('pages.be.files');
    }

    function json()
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $data = DataFile::orderBy('id', 'DESC')->get();
        return DataTables::of($data)
                    ->addIndexColumn()
                    ->editColumn('options', function($row){
                        $edit = route('file.edit', $row->id);
                        $btn = "&emsp;<a href='{$edit}' class='btn btn-sm btn-warning modal-show edit' title='Form Edit Foto'><i class='fa fa-pencil'></i></a> <button type='button' class='btn btn-sm btn-danger' id='destroy' data-id='".$row->id."'><i class='fa fa-trash'></i></button>";
                        return $btn;
                    })
                    ->editColumn('file', function($row){
                        $file = "<a href='".url('assets/files/file/'.$row->file.'?time='.time())."' target='_blank'><img src=".url('assets/frontend/img/file-logo.png'.'?time='.time())." width='100px'></a>";
                        return $file;
                    })
                    ->editColumn('status', function($row){
                        if($row->status == 1){
                            $status = "<label class='switch switch-primary'><input data-id='".$row->id."' type='checkbox' id='status' checked ><span></span></label>";
                        }else{
                            $status = "<label class='switch switch-primary'><input data-id='".$row->id."' type='checkbox' id='status'><span></span></label>";
                        }
                        return $status;
                    })
                    ->editColumn('created_at', function($row){
                        return $row->created_at != NULL ? \Helper::tgl_indo($row->created_at) : "-";
                    })
                    ->editColumn('updated_at', function($row){
                        return $row->updated_at != NULL ? \Helper::tgl_indo($row->updated_at) : "-";
                    })
                    ->rawColumns(['options', 'file', 'status'])
                    ->toJson();
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $model = new DataFile();
        return view('pages.be.form_file', compact('model'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ValidationRequest $request)
    {
        try {
            $data = new DataFile();
            $file = $request->file('file');
            $filename = strtolower('file-'.Str::slug(preg_replace('/\..+$/', '', $file->getClientOriginalName()), '-') ).'.'.$request->file->extension();
            $file->move("assets/files/file/", $filename);
            $data->name = preg_replace('/\..+$/', '', $file->getClientOriginalName());
            $data->file = $filename;
            $data->created_at = Carbon::now('Asia/Jakarta');
            $data->updated_at = null;
            $data->save();
            \Helper::log(\Auth::user()->username, "Menambah data file : ".$data->name);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil menambah file!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\File  $file
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $model = DataFile::findOrFail($id);
        return view('pages.be.form_file', compact('model'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\File  $file
     * @return \Illuminate\Http\Response
     */
    public function update_file(ValidationRequest $request)
    {
        try {
            $id = $request->id;
            $files = DataFile::findOrFail($id);
            if(file_exists("assets/files/file/".$files->file)){
                File::delete('assets/files/file/'.$files->file);
            }
            $file = $request->file('file');
            $filename = strtolower('file-'.Str::slug(preg_replace('/\..+$/', '', $file->getClientOriginalName()), '-')).'.'.$request->file->extension();
            $path = $file->move("assets/files/file/", $filename);
            //create backupdata
            // Storage::disk('SFTP')->putFileAs(Helper::web_config('npsn')."/assets/files/file/", $path, $filename);
            $data = array(
                'name' => preg_replace('/\..+$/', '', $file->getClientOriginalName()),
                'file' => $filename,
                'updated_at' => Carbon::now('Asia/Jakarta')
            );
            $files->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate data file : ".$files->name);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil mengupdate file!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    public function update_status(Request $request){
        try {
            $id = $request->id;
            $files = DataFile::findOrFail($id);
            if($files->status == 0){
                $data = array('status' => '1', 'updated_at' => Carbon::now('Asia/Jakarta'));
            }else{
                $data = array('status' => '0', 'updated_at' => Carbon::now('Asia/Jakarta'));
            }
            $files->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate status data file : ".$files->name);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil mengubah status file!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\File  $file
     * @return \Illuminate\Http\Response
     */
    public function remove(Request $request)
    {
        try {
            $id = $request->input('id');
            $files = DataFile::findOrFail($id);
            if(file_exists("assets/files/file/".$files->file)){
                File::delete('assets/files/file/'.$files->file);
            }
            $files->delete();
            \Helper::log(\Auth::user()->username, "Menghapus data file : ".$files->name);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil menghapus file!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }
}
