<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Models\Associate;
use App\Http\Models\Education;
use App\Http\Models\Home;
use App\Http\Models\Mooban;
use App\Http\Models\Tambon;
use App\Http\Models\Amphur;
use App\Http\Models\People;
use App\Http\Models\Position;
use App\Http\Models\User as TrackingUser;
use App\Http\Models\User;
use Illuminate\Http\Request;
use Exception;
use Image;
class PeopleController extends Controller
{

    /**
     * Display a listing of the people.
     *
     * @return Illuminate\View\View
     */
    public function index()
    {
        $peopleObjects = People::with('home', 'mooban', 'position', 'education', 'associate', 'user', 'trackinguser')->paginate(25);

        return view('people.index', compact('peopleObjects'));
    }

    /**
     * Show the form for creating a new people.
     *
     * @return Illuminate\View\View
     */
    public function create()
    {
        $homes = array();#Home::pluck('address', 'id')->all();
        $moobans = Mooban::pluck('name', 'id')->all();
        $positions = Position::pluck('name', 'id')->all();
        $education = Education::pluck('name', 'id')->all();
        $associates = Associate::pluck('name', 'id')->all();
       
        $users = User::pluck('name', 'id')->all();
        $trackingUsers = TrackingUser::pluck('name', 'id')->all();
        $moobans = array();
        $tambons = array();
        $amphurs = Amphur::pluck('name_th', 'id')->all();
        return view('people.create', compact('moobans', 'tambons', 'amphurs', 'homes', 'moobans', 'positions', 'education', 'associates', 'users', 'trackingUsers'));
    }

    /**
     * Store a new people 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);

            People::create($data);

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

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

    /**
     * Display the specified people.
     *
     * @param int $id
     *
     * @return Illuminate\View\View
     */
    public function show($id)
    {
        $people = People::with('home', 'mooban', 'position', 'education', 'associate', 'user', 'trackinguser')->findOrFail($id);

        return view('people.show', compact('people'));
    }

    /**
     * Show the form for editing the specified people.
     *
     * @param int $id
     *
     * @return Illuminate\View\View
     */
    public function edit($id)
    {
        $people = People::findOrFail($id);
        $homes = Home::pluck('address', 'id')->all();
        $moobans = Mooban::pluck('name', 'id')->all();
        $positions = Position::pluck('name', 'id')->all();
        $education = Education::pluck('name', 'id')->all();
        $associates = Associate::pluck('name', 'id')->all();
        $users = User::pluck('name', 'id')->all();
        $trackingUsers = TrackingUser::pluck('name', 'id')->all();
        $moobans = Mooban::pluck('name', 'id')->all();
        $tambons = Tambon::pluck('name', 'id')->all();
        $amphurs = Amphur::pluck('name_th', 'id')->all();
        return view('people.edit', compact('moobans', 'tambons', 'amphurs', 'people', 'homes', 'moobans', 'positions', 'education', 'associates', 'users', 'trackingUsers'));
    }

    /**
     * Update the specified people 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);

            $people = People::findOrFail($id);
            $people->update($data);

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

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

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

            return redirect()->route('people.people.index')
                ->with('success_message', 'ลบข้อมูล People เรียบร้อยแล้วค่ะ');
        } 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 = [
            'idcard' => 'nullable|string|min:0|max:13',
            'homes_id' => 'nullable',
            'moobans_id' => 'nullable',
            'gender' => 'nullable',
            'name' => 'nullable|string|min:0|max:100',
            'born' => 'nullable',
            'age' => 'nullable|numeric|min:-32768|max:32767',
            'tel' => 'nullable|string|min:0|max:45',
            'positions_id' => 'nullable',
            'educations_id' => 'nullable',
            'residence' => 'nullable',
            'residence_detail' => 'nullable|string|min:0|max:150',
            'vote_location' => 'nullable',
            'associates_id' => 'nullable',
            'image' => ['nullable', 'file'],
            'users_id' => 'nullable',
            'tracking_users_id' => 'nullable',
            'etc' => 'nullable|string|min:0|max:250',
            'lat' => 'nullable|numeric|min:-9|max:9',
            'lon' => 'nullable|numeric|min:-9|max:9',
        ];

        $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;

    }
}
