<?php

namespace App\Http\Controllers\Backend;

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

class SubCategoryWhereElseController extends Controller
{
    private $fileHelper;

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

    public function index($fromDate = null, $toDate = null)
    {
        // $fromDateFormatted = date('Y-m-d', strtotime($fromDate ?? date('Y-m-d'))) . ' 00:0:00';
        // $toDateFormatted = date('Y-m-d', strtotime($toDate ?? date('Y-m-d'))) . ' 23:59:59';

        // $dateConditions = [
        //     ['sub_category.created_at', '>=', $fromDateFormatted],
        //     ['sub_category.created_at', '<=', $toDateFormatted],
        // ];

        $data = SubCategoryModel::where('category_id', '2')
            ->where('active', '1')
            // ->where($dateConditions)
            ->get();

        return View::make("backend/sub-category-where-else/index")
            ->with('itemView', $data)
            ->with('fromDateView', $fromDate)
            ->with('toDateView', $toDate);
    }

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

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

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


        // $dateObject = DateTime::createFromFormat('d-m-Y', $due_date);
        // $formattedDate = $dateObject->format('Y-m-d'); // Convert to YYYY-MM-DD

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

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

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

        // prepared data
        $data = [
            'category_id' => 2,
            // 'due_date' => $formattedDate,
            'name' => $name,
            'name_en' => $name_en,
            // 'description' => $description,
            // 'description_en' => $description_en,
            'created_at' => new DateTime(),
            'updated_at' => new DateTime(),
        ];

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

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

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

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

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

    public function update(Request $request)
    {
        // keep data en
        $id = $request->input('id');
        // $due_date = $request->input('due_date');
        $name = $request->input('name');
        $name_en = $request->input('name_en');
        // $description = $request->input('description');
        // $description_en = $request->input('description_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(), [
            // 'due_date' => 'required',
            'name' => 'required',
            'name_en' => 'required',
            // 'description' => 'required',
            // 'description_en' => 'required',
            'avatar' => $imgReq
        ]);

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


        // $dateObject = DateTime::createFromFormat('d-m-Y', $due_date);
        // $formattedDate = $dateObject->format('Y-m-d'); // Convert to YYYY-MM-DD
        $data = [
            'category_id' => 2,
            // 'due_date' => $formattedDate,
            'name' => $name,
            'name_en' => $name_en,
            // 'description' => $description,
            // 'description_en' => $description_en,
            'active' => $active,
            'updated_at' => new DateTime(),
        ];

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

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

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

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

        // delete sub
        SubCategoryModel::where('id', '=', $id)->delete();

        // delete article

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

    public function uploadImageAvatar($request, $id)
    {
        // local path
        $localPath = '/uploads/where-else/sub-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
        ];
        SubCategoryModel::where('id', $id)
            ->update($dataImage);
    }
}
