<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Http\Controllers\Helpers\FileHelperController;
use App\Http\Models\CategoryModel;
use DateTime;
use Redirect;
use Validator;
use View;
use File;
use Intervention\Image\Facades\Image;


class CategoryController extends Controller
{
    private $fileHelper;

    public function __construct(
        FileHelperController  $fileHelperAccess
    ) {
        // Data accessor
        $this->fileHelper = $fileHelperAccess;
    }

    public function index()
    {
        $data = CategoryModel::get();
        return View::make("backend/category/index")
            ->with('itemView', $data);
    }

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

    public function insert(Request $request)
    {
        // keep data en
        $name = $request->input('name');
        $name_en = $request->input('name_en');
        $avatar = $request->file('avatar');

        // validate
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'name_en' => 'required',
        ]);

        if ($validator->fails()) {
            return Redirect::to("category/add")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", "Data can't empty");
        }

        // Image empty
        if (empty($avatar)) {
            return Redirect::to("category/add")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", "Please choose picture");
        }

        // Check name exist
        $countExist = CategoryModel::where('name', '=', $name)
            ->orWhere('name_en', '=', $name_en)
            ->count();

        if ($countExist > 0) {
            return Redirect::to("category/add")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Name already exist');
        }

        // check file
        if (!empty($avatar)) {
            $isFileTooLarge = $this->fileHelper->checkFileSize5MB($avatar->getSize());
            if ($isFileTooLarge) {
                return Redirect::to("category/add")
                    ->withInput()
                    ->with("messageFail", "Fail")
                    ->with("messageDetail", 'File too large, file less then 10MB');
            }
        }


        // prepared data
        $data = [
            'name' => $name,
            'name_en' => $name_en,
            'active' => 1,
            'created_at' => new DateTime(),
            'updated_at' => new DateTime(),
        ];


        // insert to database
        $result =  CategoryModel::insertGetId($data);
        if ($result > 0) { // insert success then return ID

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

            // redirect with message
            return Redirect::to("category")
                ->with("messageSuccess", "Success")
                ->with("messageDetail", 'Added success');
        } else { // insert fail
            return Redirect::to("category/add")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Added category fail');
        }
    }

    public function edit($id)
    {
        // get by id
        $data = CategoryModel::where('id', $id)->first();
        if (is_null($data)) { // not found
            return Redirect::to("category")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Not found data');
        }

        return View::make('backend/category/edit')
            ->with('idView', $id)
            ->with('itemView', $data);
    }

    public function update(Request $request)
    {
        // keep data en
        $id = $request->input('id');
        $name = $request->input('name');
        $name_en = $request->input('name_en');
        $active = $request->input('active');

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

        // validate
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'name_en' => 'required',
            'avatar' => $imgReq
        ]);

        if ($validator->fails()) {
            return Redirect::to("category/edit/" . $id)
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Data cannot be empty');
        }

        // Exist
        $countExist = CategoryModel::where('id', '!=', $id)
            ->where(function ($query) use ($name, $name_en) {
                $query->where('name', '=', $name)
                    ->orWhere('name_en', '=', $name_en);
            })
            ->count();


        if ($countExist > 0) {

            return Redirect::to("category/edit/" . $id)
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Name already exist');
        }

        $data = [
            'name' => $name,
            'name_en' => $name_en,
            'active' => $active,
            'updated_at' => new DateTime(),
        ];

        // update to database
        CategoryModel::where('id', $id)
            ->update($data);

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

        // redirect with message
        return Redirect::to("category")
            ->withInput()
            ->with("messageSuccess", "Success")
            ->with("messageDetail", 'Updated success');
    }

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

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

            return response()->json([
                'status' => true,
                'message' => "Deleted success"
            ]);

            // return Redirect::to("category")
            //     ->with("messageSuccess", "Success")
            //     ->with("messageDetail", 'Deleted success');
        } else { // return false, fail
            return response()->json([
                'status' => false,
                'message' => "Deleted fail"
            ]);
            // return Redirect::to("category")
            //     ->withInput()
            //     ->with("messageFail", "Fail")
            //     ->with("messageDetail", 'Deleted fail');
        }
    }

    public function uploadImage($request, $id)
    {
        // local path
        $localPath = '/uploads/category/' . $id;

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

        // rename
        $imgName = 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);
        }

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

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

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

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