<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use App\Http\Models\Electorate;
use App\Http\Models\Mooban;
use App\Http\Models\Tambon;
use App\Http\Models\Amphur;
use App\Http\Models\User;
use Illuminate\Http\Request;
use Exception;

class UsersController extends Controller
{

    /**
     * Display a listing of the users.
     *
     * @return Illuminate\View\View
     */
    public function index()
    {
        $users = User::paginate(25);

        return view('users.index', compact('users'));
    }

    /**
     * Show the form for creating a new user.
     *
     * @return Illuminate\View\View
     */
    public function create()
    {
        $moobans = Mooban::pluck('name','id')->all();
$tambons = Tambon::pluck('name','id')->all();
$amphurs = Amphur::pluck('name_th','id')->all();
$electorates = Electorate::pluck('name','id')->all();
        
        return view('users.create', compact('moobans','tambons','amphurs','electorates'));
    }

    /**
     * Store a new user in the storage.
     *
     * @param Illuminate\Http\Request $request
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        try {
            
            $data = $this->getData($request);
            
            User::create($data);

            return redirect()->route('users.user.index')
                ->with('success_message', 'เพิ่ม User ใหม่แล้ว');
        } catch (Exception $exception) {

            return back()->withInput()
                ->withErrors(['unexpected_error' => 'พบข้อผิดพลาดค่ะ!']);
        }
    }

    /**
     * Display the specified user.
     *
     * @param int $id
     *
     * @return Illuminate\View\View
     */
    public function show($id)
    {
        $user = User::with('mooban','tambon','amphur','electorate')->findOrFail($id);

        return view('users.show', compact('user'));
    }

    /**
     * Show the form for editing the specified user.
     *
     * @param int $id
     *
     * @return Illuminate\View\View
     */
    public function edit($id)
    {
        $user = User::findOrFail($id);
        $moobans = Mooban::pluck('name','id')->all();
$tambons = Tambon::pluck('name','id')->all();
$amphurs = Amphur::pluck('name_th','id')->all();
$electorates = Electorate::pluck('name','id')->all();

        return view('users.edit', compact('user','moobans','tambons','amphurs','electorates'));
    }

    /**
     * Update the specified user in the storage.
     *
     * @param int $id
     * @param Illuminate\Http\Request $request
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function update($id, Request $request)
    {
        try {
            
            $data = $this->getData($request);
            
            $user = User::findOrFail($id);
            $user->update($data);

            return redirect()->route('users.user.index')
                ->with('success_message', 'ปรับปรุงข้อมูล User เรียบร้อยแล้วค่ะ');
        } catch (Exception $exception) {

            return back()->withInput()
                ->withErrors(['unexpected_error' => 'พบข้อผิดพลาดค่ะ!']);
        }        
    }

    /**
     * Remove the specified user from the storage.
     *
     * @param int $id
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function destroy($id)
    {
        try {
            $user = User::findOrFail($id);
            $user->delete();

            return redirect()->route('users.user.index')
                ->with('success_message', 'ลบข้อมูล User เรียบร้อยแล้วค่ะ');
        } catch (Exception $exception) {

            return back()->withInput()
                ->withErrors(['unexpected_error' => 'พบข้อผิดพลาดค่ะ!']);
        }
    }

    
    /**
     * Get the request's data from the request.
     *
     * @param Illuminate\Http\Request\Request $request 
     * @return array
     */
    protected function getData(Request $request)
    {
        $rules = [
                'name' => 'nullable|string|min:0|max:70',
            'tel' => 'nullable|string|min:0|max:30',
            'email' => 'nullable|string|min:0|max:60',
            'username' => 'nullable|string|min:0|max:20',
            'password' => 'nullable|string|min:0|max:70',
            'permission' => 'nullable',
            'image' => ['nullable','file'],
            'etc' => 'nullable|string|min:0|max:500',
            'moobans_id' => 'nullable',
            'tambons_id' => 'nullable',
            'amphurs_id' => 'nullable',
            'electorates_id' => 'nullable', 
        ];
        
        $data = $request->validate($rules);
        if ($request->has('custom_delete_image')) {
            $data['image'] = null;
        }
        if ($request->hasFile('image')) {
            $data['image'] = $this->moveFile($request->file('image'));
        }

        return $data;
    }
  
    /**
     * Moves the attached file to the server.
     *
     * @param Symfony\Component\HttpFoundation\File\UploadedFile $file
     *
     * @return string
     */
  private function moveFile($file )
	{
		@mkdir('upload');
		@mkdir('upload/image');
		@mkdir('upload/image/' . date('Y-m') . '/');
		@mkdir('upload/image/' . date('Y-m') . '/');
		$path = 'upload/image/' . date('Y-m') . '/';
		$url = 'user_' . time() . "." . $file->getClientOriginalExtension();
		$img = Image::make($file->getRealPath());
		$width = Image::make($file->getRealPath())->width();
		$height = Image::make($file->getRealPath())->height();
		#-----------------------------------------------------------------
		$fix_wi = 1600;
		$fix_hi = 1200;
		if ($width > $height) {
			$fix_hi = 1200;
			$fix_wi = 1600;
		} else {
			$fix_wi = 1200;
			$fix_hi = 1600;
		}
		$img->resize($fix_wi, null, function ($constraint) {
			$constraint->aspectRatio();
		});
		$img->save($path . $url, 85);
		return $path . $url;

	}
}
