<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\ValidationRequest;
use App\Blog;
use App\Kegiatan;
use Helper;
use Carbon\Carbon;
use File;
use Image;
use Alert;
use Hash;
use Illuminate\Database\QueryException;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;

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

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

    public function index()
    {
        $blog = Blog::from('blogs as a')
                ->leftJoin('users as b', 'b.username', '=', 'a.author')
                ->select('a.*', 'b.name as nama_author', 'b.foto as foto_author')
                ->where('a.status', '1')
                ->orderBy('a.created_at', 'DESC')
                ->limit(5)
                ->get();
        $kegiatan = Kegiatan::where('status', '1')->orderBy('created_at', 'DESC')->limit(5)->get();
        $model = User::where('username', \Auth::user()->username)->first();
        return view('pages.be.profile', compact('model', 'blog', 'kegiatan'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

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

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);
            if($request->password != NULL){
                $this->validate($request, [
                    'name' => 'required',
                    'email' => 'required|email',
                    'password' => 'confirmed',
                    'password_confirmation' => ''
                ],[
                    'name.required' => 'Nama tidak boleh kosong!',
                    'email.required' => 'Email tidak boleh kosong!',
                    'password.confirmed' => 'Password dan Password Confirmation harus cocok!',
                ]);
                $data = array(
                    'name' => $request->name,
                    'email' => $request->email,
                    'password' => Hash::make($request->password),
                    'updated_at' => Carbon::now('Asia/Jakarta')
                );
            }else{
                $this->validate($request, [
                    'name' => 'required',
                    'email' => 'required|email',
                ],[
                    'name.required' => 'Nama tidak boleh kosong!',
                    'email.required' => 'Email tidak boleh kosong!',
                ]);

                $data = array(
                    'name' => $request->name,
                    'email' => $request->email,
                    'updated_at' => Carbon::now('Asia/Jakarta')
                );
            }
            $user->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate profile!");
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil update profile!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    public function resetToken($id)
    {
        try {
            $user = User::findOrFail($id);
            $data = array(
                'remember_token' => null,
                'api_token' => null,
                'device_token' => null,
                'updated_at' => Carbon::now('Asia/Jakarta'),
            );
            $user->update($data);
            \Helper::log(\Auth::user()->username, "Mereset token android!");
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Semua token tersimpan berhasil direset!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    public function update_foto(ValidationRequest $request)
    {
        try {
            $username = $request->username;
            $cek = User::where('username', $username)->first();
            if(file_exists("assets/files/profile/".$cek->foto)){
                File::delete('assets/files/profile/'.$cek->foto);
                if(file_exists("assets/files/profile/thumbnail/".$cek->foto)){
                    File::delete('assets/files/profile/thumbnail/'.$cek->foto);
                }
            }
            if(!File::isDirectory('assets/files/profile')){
                File::makeDirectory('assets/files/profile', 0755, true, true);
            }
            if(!File::isDirectory('assets/files/profile/thumbnail')) {
                File::makeDirectory('assets/files/profile/thumbnail', 0755, true, true);
            }
            $file = $request->file('foto');
            $filename = strtolower('foto-'.Helper::acakstring(8)).'.'.$request->foto->extension();
            $path = "assets/files/profile/".$filename;
            $uploaded = Helper::resizeImage($file, $path, 600, 600);
            if($uploaded){
                $thumbnailsource = "assets/files/profile/".$filename;
                $thumbnailpath = "assets/files/profile/thumbnail/". $filename;
                Helper::createThumbnail($thumbnailsource, $thumbnailpath, 200, 200);
            }
            //create backupdata
            // Storage::disk('SFTP')->putFileAs(Helper::web_config('npsn')."/assets/files/profile/", $path, $filename);
            // Storage::disk('SFTP')->putFileAs(Helper::web_config('npsn')."/assets/files/profile/thumbnail", $thumbnailpath, $filename);
            $data = array(
                'foto' => $filename,
                'updated_at' => Carbon::now('Asia/Jakarta')
            );
            User::where('username', $username)->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate foto profile!");
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil mengganti foto profile!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        //
    }
}
