<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Http\Models\UserModel;
use DateTime;
use Redirect;
use Validator;
use View;
use Hash;
use File;
use Intervention\Image\Facades\Image;

class UserController extends Controller
{
    public function index()
    {
        $userObj = UserModel::get();
        return View::make("backend/user/index")
            ->with('userView', $userObj);
    }

    public function add()
    {
        return View::make("backend/user/add");
    }

    public function insert(Request $request)
    {
        // keep data en
        $role = $request->input('role');
        $first_name = $request->input('first_name');
        $last_name = $request->input('last_name');
        $email = $request->input('email');
        $password = $request->input('password');

        $avatar = $request->file('avatar');

        // validate
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'first_name' => 'required',
            'last_name' => 'required',
            'password' => 'required',
            'avatar' => 'required|image|mimes:jpeg,png,jpg|max:10240',
        ]);

        if ($validator->fails()) {
            return Redirect::to("user")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Data can not be empty');
        }

        // check existing email
        $e = UserModel::where('email', $email)->count();
        if ($e > 0) {
            return Redirect::to("user")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Email already exist');
        }

        // prepared data
        $data = [
            'first_name' => $first_name,
            'last_name' => $last_name,
            'email' => $email,
            'password' => Hash::make($password),
            'role' => $role,
            'created_at' => new DateTime(),
            'updated_at' => new DateTime(),
        ];

        // insert to database
        $result = UserModel::insertGetId($data);

        if ($result > 0) { // insert success then return ID

            // Image
            if (!empty($avatar)) {
                $this->uploadImage($request, $result);
            }


            return Redirect::to("user")
                ->with("messageSuccess", "Success")
                ->with("messageDetail", 'Added success');
        } else { // insert fail
            return Redirect::to("user")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Add unsuccessfully');
        }
    }

    public function edit($userId)
    {
        // get by id
        $data = UserModel::where('id', $userId)
                ->first();
        if (is_null($data)) { // not found

            return Redirect::to("user")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Not found data');
        }

        return View::make('backend/user/edit')
            ->with('userIdView', $userId)
            ->with('userView', $data);
    }

    public function update(Request $request)
    {
        // keep data en
        $role = $request->input('role');
        $userId = $request->input('userId');
        $active = $request->input('active');
        $first_name = $request->input('first_name');
        $last_name = $request->input('last_name');
        $email = $request->input('email');
        $password = $request->input('password');

        $avatar = $request->file('avatar');
        $imgReq = $avatar ? 'required|image|mimes:jpeg,png,jpg|max:10240' : '';

        // validate
        $validator = Validator::make($request->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|email',
            'avatar' => $imgReq,
        ]);

        if ($validator->fails()) {
            return Redirect::to("user")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Data can not be empty');
        }


        // check existing email
        if (UserModel::where('id', '!=', $userId)
                ->where('email', '=', $email)->count() > 0) {
            return Redirect::to("user")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Email already exist');
        }

        if ($password == "") {
            $data = [
                'active' => $active,
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $email,
                'role' => $role,
                'updated_at' => new DateTime(),
            ];
        } else {
            $data = [
                'active' => $active,
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $email,
                'role' => $role,
                'updated_at' => new DateTime(),
                'password' => Hash::make($password)
            ];
        }

       UserModel::where('id', $userId)
                ->update($data);

        // Image
        if (!empty($avatar)) {
            $this->uploadImage($request, $userId);
        }

        return Redirect::to("user")
            ->with("messageSuccess", "Success")
            ->with("messageDetail", 'Updated success');
    }

    public function delete(Request $request)
    {
        $userId = $request->input('item_id');

        $hasUser =  UserModel::where('id', $userId)
                ->first();
                
        if (!$hasUser) { // not found
            return Redirect::to("user")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", "Not found");
        }

        // delete user in database
        $result = UserModel::where('id', '=', $userId)
                ->delete();
        if ($result) { // return true, success

            // delete folder
            File::deleteDirectory('uploads/user/' . $userId);


            return response()->json([
                'status' => "Success",
                'message' => "Delete successfully"
            ]);
        } else { // return false, fail
            return response()->json([
                'status' => "Fail",
                'message' => "Delete unsuccessfully"
            ]);
        }
    }

    public function uploadImage($request, $result)
    {
        $localPath = '/uploads/user/' . $result;
        $image = $request->file('avatar');
        $imgName = uniqid() . time() . '.' . $image->extension();

        // destination
        $destinationUrl = url($localPath);
        $destinationPath = public_path($localPath);

        // create folder
        if (File::isDirectory($destinationPath . '/original/') == false) {
            File::makeDirectory($destinationPath . '/original/', 0777, true);
        }
        if (File::isDirectory($destinationPath . '/thumbnail/') == false) {
            File::makeDirectory($destinationPath . '/thumbnail/', 0777, true);
        }

        $img = Image::make($image->path());

        // remove old
        $userObj = UserModel::where('id', $result)
                ->first();
        if ($userObj != null) {
            $oldPathO = $destinationPath . '/original/' . $userObj->image_name;
            $oldPathT = $destinationPath . '/thumbnail/' . $userObj->image_name;

            if (File::exists($oldPathO)) {
                File::delete($oldPathO);
            }

            if (File::exists($oldPathT)) {
                File::delete($oldPathT);
            }
        }

        // original
        $img->save($destinationPath . '/original/' . $imgName);

        // thumbnail
        $img->resize(300, 300, function ($constraint) {
            $constraint->aspectRatio();
        })->save($destinationPath . '/thumbnail/' . $imgName);

        // update
        $dataImage = [
            'image_url' => $destinationUrl,
            'image_name' => $imgName
        ];
        
        UserModel::where('id', $result)
                ->update($dataImage);
    }
    

    public function returnJsonFieldEmpty($fieldName)
    {
        return response()->json([
            'status' => 'Fail',
            'message' => $fieldName . ' ' . "can not be empty"
        ]);
    }

    public function returnJsonErrorMsg($message)
    {
        return response()->json([
            'status' => 'Fail',
            'message' => $message
        ]);
    }

    public function returnJsonSuccessMsg($message)
    {
        return response()->json([
            'status' => 'Success',
            'message' => $message
        ]);
    }
    
}
