<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\ApiCode;
use App\Models\Person;
use App\Models\Phone;
use App\Models\Request as MyRequest;
use App\Models\Sequence;
use App\Models\DeletedSequence;
use App\Models\Year;

use Carbon\Carbon;
use Validator;

class PersonController extends AppBaseController
{
    public function __construct()
    {
        $this->middleware('auth:api',);
    }

    public function all(Request $request)
    {

        $limit = 100;
        if ($request->query("limit") != null)
            $limit = $request->query('limit');


        $persons =  Person::where(
            function ($query) use ($request) {
                if ($request->query("id") != null) {
                    $id = $request->query("id");
                    if ($id != 0 && $id != -1) {
                        if ($request->query("next") != null)
                            return $query->where('id', '>', $id)->where('is_deleted', 0);
                        else
                        if ($request->query("back") != null)
                            return $query->where('id', '<', $id)->where('is_deleted', 0);
                        else
                            return $query->where('id', $id);
                    }
                }
            }
        )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("name") != null) {
                        $name = $request->query("name");
                        return $query->where('name', 'like', '%' . $name . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("city") != null) {
                        $city = $request->query("city");
                        return $query->where('city', 'like', '%' . $city . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("degree") != null) {
                        $degree = $request->query("degree");
                        return $query->where('degree',  $degree);
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("record_no") != null) {
                        $record_no = $request->query("record_no");
                        return $query->where('record_no', 'like', '%' . $record_no . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("logo") != null) {
                        $logo = $request->query("logo");
                        return $query->where('logo', 'like', '%' . $logo . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("nativity") != null) {
                        $nativity = $request->query("nativity");
                        return $query->where('nativity', 'like', '%' . $nativity . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("address") != null) {
                        $address = $request->query("address");
                        return $query->where('address', 'like', '%' . $address . '%');
                    }
                }
            )

            ->where(
                function ($query) use ($request) {
                    if ($request->query("trade_type") != null) {
                        $trade_type = $request->query("trade_type");
                        return $query->where('trade_type', 'like', '%' . $trade_type . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("mother_name") != null) {
                        $mother_name = $request->query("mother_name");
                        return $query->where('mother_name', 'like', '%' . $mother_name . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("location") != null) {
                        $location = $request->query("location");
                        return $query->where('location', 'like', '%' . $location . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("digit") != null) {
                        $digit = $request->query("digit");
                        return $query->where('digit', 'like', '%' . $digit . '%');
                    }
                }
            )

            ->where(
                function ($query) use ($request) {
                    if ($request->query("personality_number") != null) {
                        $personality_number = $request->query("personality_number");
                        return $query->where('personality_number', 'like', '%' . $personality_number . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("deathHelp") != null) {
                        $deathHelp = $request->query("deathHelp");
                        return $query->whereHas('grantPeople', function ($query) use ($deathHelp) {
                            return  $query->where('year', $deathHelp);
                        });
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("out_from") != null) {
                        $out_from = $request->query("out_from");
                        return $query->where('out_from',  $out_from);
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("remarks") != null) {
                        $remarks = $request->query("remarks");
                        return $query->where('remarks', 'like', '%' . $remarks . '%');
                    }
                }
            )


            ->where(
                function ($query) use ($request) {
                    if ($request->query("status") != null) {
                        $status = $request->query("status");
                        return $query->where('status',  $status);
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("is_deleted") != null) {
                        $is_deleted = $request->query("is_deleted");
                        return $query->where('is_deleted', $is_deleted);
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("status_description") != null) {
                        $status_description = $request->query("status_description");
                        return $query->where('status_description', 'like', '%' . $status_description . '%');
                    }
                }
            )

            ->where(
                function ($query) use ($request) {
                    if ($request->query("before") != null) {
                        $before = $request->query("before");
                        return $query->where('hire_date', '<',  date("Y-m-d", strtotime($before)));
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("after") != null) {
                        $after = $request->query("after");
                        return $query->where('hire_date', '>', date("Y-m-d", strtotime($after)));
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("from") != null) {
                        $from = $request->query("from");
                        return $query->where('hire_date', '>=', date("Y-m-d", strtotime($from)));
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("to") != null) {
                        $to = $request->query("to");
                        return $query->where('hire_date', '<=', date("Y-m-d", strtotime($to)));
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("equals") != null) {
                        $equals = $request->query("equals");
                        return $query->whereDate('hire_date',  date("Y-m-d", strtotime($equals)));
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("dname") != null) {
                        $dname = $request->query("dname");
                        return $query->where('name',  'like', '%' . $dname . '%');
                    }
                }
            )

            ->where(
                function ($query) use ($request) {
                    if ($request->query("mother") != null) {
                        $mother = $request->query("mother");
                        return $query->where('mother_name',  'like', '%' . $mother . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("digit") != null) {
                        $digit = $request->query("digit");
                        return $query->where('digit', 'like', '%' . $digit . '%');
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("birthday") != null) {
                        $birthday = $request->query("birthday");
                        if ($request->query("ageAfter") == 1)
                            return $query->where('year', '>',  $birthday);

                        if ($request->query("ageBefore") == 1)
                            return $query->where('year', '<',  $birthday);

                        if ($request->query("ageEquals") == 1)
                            return $query->where('year',   $birthday);
                    }
                }
            )->where(
                function ($query) use ($request) {
                    if ($request->query("hire_date") != null) {
                        $hire_date = $request->query("hire_date");
                        return $query->where('hire_date', date("Y-m-d", strtotime($hire_date)));
                    }
                }
            )

            ->where(
                function ($query) use ($request) {
                    if ($request->query("year") != null) {
                        if ($request->query("paid") != null)
                            if ($request->query("paid") == 1)
                                $query->whereHas(
                                    'years',
                                    function ($query) use ($request) {

                                        $year = $request->query("year");

                                        return $query->where('year',   $year);
                                    }
                                );
                            else
                                $query->whereDoesntHave(
                                    'years',
                                    function ($query) use ($request) {
                                        if ($request->query("paid") != null) {
                                            $year = $request->query("year");
                                            return $query->where('year',   $year);
                                        }
                                    }
                                );
                    } else if ($request->query("newAt") != null || $request->query("newFor") != null) {
                        return $query->whereHas(
                            'years',
                            function ($query) use ($request) {

                                $newAt = $request->query("newAt");
                                $newFor = $request->query("newFor");
                                if ($newFor == null && $newAt != null)
                                    return $query->whereDate('created_at', '>=',   $newAt);
                                if ($newAt == null && $newFor != null)
                                    return $query->whereDate('created_at', '<=',   $newFor);
                                if ($newFor != null && $newAt != null)
                                    return $query->whereDate('created_at', '<=',   $newFor)->whereDate('created_at', '>=',   $newAt);
                            }
                        )->where("user_id", null);
                    } else if ($request->query("yearSequence") != null) {
                        return $query->whereHas(
                            'years',
                            function ($query) use ($request) {


                                $yearSequence = $request->query("yearSequence");
                                $yearSequenceYear = $request->query("yearSequenceYear");
                                if ($yearSequence != null)
                                    return $query->where('number', $yearSequence)
                                        ->where('year', $yearSequenceYear);
                            }
                        );
                    }
                }
            );

        if ($request->query("id") != null) {
            $id = $request->query("id");
            if ($id == 0) {
                $data = $persons->orderBy('id', 'DESC')->first();
                $data = [$data];
            } else if ($id == -1) {
                $data = $persons->orderBy('id', 'ASC')->first();
                $data = [$data];
            } else {
                if ($request->query("back") != null) {
                    $data = $persons->orderBy('id', 'DESC')->first();
                    $data = [$data];
                } else
                if ($request->query("next") != null) {
                    $data = $persons->first();
                    $data = [$data];
                } else
                    $data = $persons->orderBy('id', 'DESC')->paginate($limit);
            }
        } else   $data = $persons->orderBy('id', 'DESC')->paginate($limit);

        return  $this->sendResponse(
            $data,
            "here are your persons!",
            ApiCode::SUCCESS,
            0
        );
    }

    public function add(Request $request)
    {

        /**
         * Class Person
         * @package App\Models
         * @version December 20, 2020, 11:19 am UTC
         *
         * @property \App\Models\User $updatedBy
         * @property \App\Models\User $user
         * @property \Illuminate\Database\Eloquent\Collection $phones
         * @property \Illuminate\Database\Eloquent\Collection $years
         * @property integer $user_id
         * @property integer $updated_by
         * @property string $name
         * @property string $city
         * @property string $hire_date
         * @property string $degree
         * @property string $record_no
         * @property string $logo
         * @property string $mailbox
         * @property string $nativity
         * @property string $address
         * @property string $trade_type
         * @property string $mother_name
         * @property string $location
         * @property string $digit
         * @property string $year
         * @property string $personality_number
         * @property string $out_from
         * @property string $remarks
         * @property boolean $status
         * @property boolean $is_deleted
         * @property string $status_description
         * @property string $birthday
         */
        $rules =
            [
                'name' => 'required',
                'city' => 'required',
                'request_id' => 'required',
                'hire_date' => 'required',
                'degree' => 'required',
            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        $old = Person::where('request_id', $request->request_id)->first();
        if ($old) {
            return $this->sendResponse(
                null,
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }

        $user = auth()->user();
        $input = $request->all();
        $requestt = MyRequest::where('id', $input['request_id'])->first();
        if ($requestt) {
            $requestt->degree =  $input['degree'];
            $requestt->save();
        }
        $input['user_id'] = $user->id;

        $sequence = DeletedSequence::where('name', 'person_id')->first();
        if ($sequence)
            $input['id'] = $sequence->sequence;
        $person = Person::create($input);
        if ($sequence)
            $sequence->delete();
        if ($request->has('phone1'))
            if ($request->phone1 != null)
                Phone::create([
                    'user_id' => $user->id,
                    'person_id' => $person->id,
                    'phone_number' => $request->phone1
                ]);
        if ($request->has('phone2'))
            if ($request->phone2 != null)
                Phone::create([
                    'user_id' => $user->id,
                    'person_id' => $person->id,
                    'phone_number' => $request->phone2
                ]);
        return $this->sendResponse([
            Person::find($person->id),
        ], "person created successfully", ApiCode::CREATED, 0);
    }

    public function edit($id, Request $request)
    {
        $person = Person::findOrFail($id);
        $user = auth()->user();


        if ($request->has('name'))
            if ($request->name != null)
                $person->name =    $request->name;


        if ($request->has('city'))
            if ($request->city != null)
                $person->city =    $request->city;


        if ($request->has('hire_date'))
            if ($request->hire_date != null)
                $person->hire_date =    $request->hire_date;


        if ($request->has('degree'))
            if ($request->degree != null)
                $person->degree =    $request->degree;


        if ($request->has('record_no'))
            if ($request->record_no != null)
                $person->record_no =    $request->record_no;

        if ($request->has('logo'))
            $person->logo =    $request->logo;

        if ($request->has('mailbox'))
            if ($request->mailbox != null)
                $person->mailbox =    $request->mailbox;

        if ($request->has('nativity'))
            if ($request->nativity != null)
                $person->nativity =    $request->nativity;

        if ($request->has('address'))
            if ($request->address != null)
                $person->address =    $request->address;

        if ($request->has('trade_type'))
            if ($request->trade_type != null)
                $person->trade_type =    $request->trade_type;

        if ($request->has('mother_name'))
            if ($request->mother_name != null)
                $person->mother_name =    $request->mother_name;

        if ($request->has('location'))
            if ($request->location != null)
                $person->location =    $request->location;

        if ($request->has('digit'))
            if ($request->digit != null)
                $person->digit =    $request->digit;

        if ($request->has('year'))
            if ($request->year != null)
                $person->year =    $request->year;

        if ($request->has('personality_number'))
            if ($request->personality_number != null)
                $person->personality_number =    $request->personality_number;

        if ($request->has('out_from'))
            if ($request->out_from != null)
                $person->out_from =    $request->out_from;

        if ($request->has('remarks'))
            if ($request->remarks != null)
                $person->remarks =    $request->remarks;

        if ($request->has('status'))
            if ($request->status != null)
                $person->status =    $request->status;

        if ($request->has('is_deleted'))
            if ($request->is_deleted != null)
                $person->is_deleted =    $request->is_deleted;

        if ($request->has('status_description'))
            if ($request->status_description != null)
                $person->status_description =    $request->status_description;

        if ($request->has('birthday'))
            if ($request->birthday != null)
                $person->birthday =    $request->birthday;

        $person->updated_by = $user->id;
        $person->save();
        return $this->sendResponse([
            Person::find($person->id),
        ], "Person updated successfully", ApiCode::SUCCESS, 0);
    }

    public function addPhone($id, Request $request)
    {

        $person = Person::findOrFail($id);
        $user = auth()->user();
        $rules =
            [
                'phone_number' => 'required',
            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }

        $input = $request->all();
        $input['user_id'] = $user->id;
        $input['person_id'] = $person->id;
        $phone = Phone::create($input);

        return $this->sendResponse(
            Phone::find($phone->id),
            "phone created successfully",
            ApiCode::CREATED,
            0
        );
    }
    public function editPhone($id, Request $request)
    {
        $phone = Phone::findOrFail($id);
        $user = auth()->user();


        if ($request->has('phone_number'))
            if ($request->phone_number != null)
                $phone->phone_number =    $request->phone_number;


        $phone->save();
        return $this->sendResponse(
            Phone::find($phone->id),
            "phone updated successfully",
            ApiCode::SUCCESS,
            0
        );
    }

    public function addYear($id, Request $request)
    {

        $person = Person::findOrFail($id);
        $user = auth()->user();
        $rules =
            [
                'year' => 'required|integer',
            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        $currentYear = Carbon::now()->year;
        $isDeleted = false;
        $sequence = DeletedSequence::where('name', 'person')->first();
        if ($sequence) {
            $isDeleted = true;
        } else {
            $isDeleted = false;
            // number
            $sequence = Sequence::where('name', 'person')->first();
            if (!$sequence) {
                $sequence = Sequence::create([
                    'name' => 'person',
                ]);
            }
        }

        $input = $request->all();
        $input['user_id'] = $user->id;


        $old = Year::where('year', $input['year'])->where('person_id', $person->id)->first();
        if ($old)
            return $this->sendResponse(null, "year exists", ApiCode::BAD_REQUEST, 0);

        if ($currentYear  ==  $input['year']) {

            if ($isDeleted) {
                $input['number'] = ($sequence->sequence);
                $sequence->delete();
            } else {
                $input['number'] = ($sequence->sequence + 1);
                $sequence->sequence += 1;
                $sequence->save();
            }
            /*   $input['number'] = ($sequence->sequence + 1);
            $sequence->sequence += 1;
            $sequence->save(); */
        } else   if ($currentYear  >  $input['year']) {
            $input['number'] = 'سدد الرسم';
        } else {
            return $this->sendResponse(null, "year exists", ApiCode::BAD_REQUEST, 0);
        }
        $input['person_id'] = $person->id;
        $year = Year::create($input);

        return $this->sendResponse(
            Year::find($year->id),
            "year created successfully",
            ApiCode::CREATED,
            0
        );
    }
    public function resetPersonSequence(Request $request)
    {
        $sequence = Sequence::where('name', 'person')->first();

        DeletedSequence::where('name',  'person')->delete();

        if (!$sequence) {
            $sequence = Sequence::create([
                'name' => 'person',
            ]);
        } else {
            $sequence->sequence = 0;
            $sequence->save();
        }
        return $this->sendResponse(
            null,
            "sequence returned to scratch",
            ApiCode::SUCCESS,
            0
        );
    }
    public function editYear($id, Request $request)
    {
        $year = Year::findOrFail($id);
        $user = auth()->user();
        if ($request->has('year'))
            if ($request->year != null) {
                if ($request->year != $year->year) {
                    $old = Year::where('year', $request->year)->where('person_id', $year->person_id)->first();
                    if ($old)
                        return $this->sendResponse(null, "year exists", ApiCode::BAD_REQUEST, 0);
                }

                $year->year =    $request->year;
            }
        if ($request->has('number'))
            if ($request->number != null)
                $year->number =    $request->number;

        $year->updated_by = $user->id;
        $year->save();
        return $this->sendResponse([
            Year::find($year->id),
        ], "year updated successfully", ApiCode::SUCCESS, 0);
    }

    public function deleteYear($id)
    {
        $currentYear = Carbon::now()->year;
        $year = Year::findOrFail($id);
        if ($year->year === $currentYear)
            DeletedSequence::create([
                'name' => 'person',
                'sequence' => $year->number
            ]);
        $year->delete();

        return $this->sendResponse(
            null,
            "year deleted successfully",
            ApiCode::SUCCESS,
            0
        );
    }
    public function delete($id)
    {
        $old = Person::findOrFail($id);
        DeletedSequence::create([
            'name' => 'person_id',
            'sequence' => $old->id
        ]);
        $old->delete();
        return $this->sendResponse(
            null,
            "company deleted successfully",
            ApiCode::SUCCESS,
            0
        );
    }
}
