<?php

namespace App\Http\Controllers;

use App\ApiCode;
use App\Models\Company;
use App\Models\Phone;
use App\Models\Sequence;
use App\Models\DeletedSequence;
use App\Models\Request as MyRequest;
use App\Models\Year;
use App\Models\CompanyDetail;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Validator;
use Log;

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


    public function all(Request $request)
    {
        Log::error($request);
        $limit = 100;
        if ($request->query("limit") != null)
            $limit = $request->query('limit');

        $companies =  Company::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("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("degree") != null) {
                        $degree = $request->query("degree");
                        return $query->where('degree',  $degree);
                    }
                }
            )
            ->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("deathHelp") != null) {
                        $deathHelp = $request->query("deathHelp");
                        return $query->whereHas('companyDetails', function ($query) use ($deathHelp) {
                            return $query->whereHas('grantPeople', function ($query) use ($deathHelp) {
                                return  $query->where('year', $deathHelp);
                            });
                        });
                    }
                }
            )
            ->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("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("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("dname") != null) {
                        $query->whereHas(
                            'companyDetails',
                            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("father") != null) {
                        $query->whereHas(
                            'companyDetails',
                            function ($query) use ($request) {
                                if ($request->query("father") != null) {
                                    $father = $request->query("father");
                                    return $query->where('father_name',  'like', '%' . $father . '%');
                                }
                            }
                        );
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("mother") != null) {
                        $query->whereHas(
                            'companyDetails',
                            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) {
                        $query->whereHas(
                            'companyDetails',
                            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) {
                        $query->whereHas(
                            'companyDetails',
                            function ($query) use ($request) {
                                if ($request->query("birthday") != null) {
                                    $birthday = $request->query("birthday");
                                    if ($request->query("ageAfter") == 1)
                                        return $query->where('birthday', '>',  $birthday);

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

                                    if ($request->query("ageEquals") == 1)
                                        return $query->where('birthday',   $birthday);
                                }
                            }
                        );
                    }
                }
            )
            ->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) {


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

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



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



    public function add(Request $request)
    {

        /**
         * Class Company
         * @package App\Models
         * @version December 20, 2020, 8:21 am UTC
         *
         * @property \App\Models\User $user
         * @property \Illuminate\Database\Eloquent\Collection $companyDetails
         * @property \Illuminate\Database\Eloquent\Collection $companyDetail1s
         * @property \Illuminate\Database\Eloquent\Collection $phones
         * @property \Illuminate\Database\Eloquent\Collection $years
         * @property integer $user_id
         * @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 boolean $status
         * @property string $status_description
         * @property string $birthday
         * @property string $param1
         * @property string $param2
         * @property string $param3
         * @property string $param4
         * @property string $param5
         * @property string $param6
         */
        $rules =
            [
                'name' => 'required',
                'request_id' => 'required',
                'city' => '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 = Company::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', 'company_id')->first();
        if ($sequence)
            $input['id'] = $sequence->sequence;
        $company = Company::create($input);
        if ($sequence)
            $sequence->delete();
        if ($request->has('phone1'))
            if ($request->phone1 != null)
                Phone::create([
                    'user_id' => $user->id,
                    'company_id' => $company->id,
                    'phone_number' => $request->phone1
                ]);
        if ($request->has('phone2'))
            if ($request->phone2 != null)
                Phone::create([
                    'user_id' => $user->id,
                    'company_id' => $company->id,
                    'phone_number' => $request->phone2
                ]);

        CompanyDetail::create([
            'user_id' => $user->id,
            'company_id' => $company->id,
            'name' => $request->first_name,
            'mother_name' => $request->mother_name,
            'father_name' => $request->father_name,
            'digit' => $request->digit,
            'birthday' => $request->year,
        ]);
        return $this->sendResponse([
            Company::find($company->id),
        ], "Company created successfully", ApiCode::CREATED, 0);
    }


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


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


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


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


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


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


        if ($request->has('logo'))

            $company->logo =    $request->logo;


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


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


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


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


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

        if ($request->has('status_description'))
            if ($request->status_description != null)
                $company->status_description =    $request->status_description;
        if ($request->has('is_deleted'))
            if ($request->is_deleted != null)
                $company->is_deleted =    $request->is_deleted;
        $company->updated_by = $user->id;
        $company->save();
        return $this->sendResponse([
            Company::find($company->id),
        ], "Company updated successfully", ApiCode::SUCCESS, 0);
    }

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

        $company = Company::findOrFail($id);
        $user = auth()->user();
        $rules =
            [
                'name' => 'required',
                'mother_name' => 'required',
                'father_name' => 'required',
                'digit' => 'required',
                'birthday' => 'required',
                'is_authorized' => '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['company_id'] = $company->id;
        $detail = CompanyDetail::create($input);

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


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


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


        if ($request->has('father_name'))
            if ($request->father_name != null)
                $detail->father_name =    $request->father_name;


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


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

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

        if ($request->has('is_authorized'))
            if ($request->is_authorized != null)
                $detail->is_authorized =    $request->is_authorized;

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

        if ($request->has('status_description'))
            if ($request->status_description != null)
                $detail->status_description =    $request->status_description;
        $detail->updated_by = $user->id;
        $detail->save();
        return $this->sendResponse(
            CompanyDetail::find($detail->id),
            "CompanyDetail updated successfully",
            ApiCode::SUCCESS,
            0
        );
    }

    public function deleteDetail($id)
    {
        $detail = CompanyDetail::findOrFail($id);
        $detail->delete();

        return $this->sendResponse(
            null,
            "CompanyDetail deleted successfully",
            ApiCode::SUCCESS,
            0
        );
    }


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

        $company = Company::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['company_id'] = $company->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 deletePhone($id)
    {
        $phone = Phone::findOrFail($id);
        $phone->delete();

        return $this->sendResponse([
            null,
        ], "phone deleted successfully", ApiCode::SUCCESS, 0);
    }

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

        $company = Company::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', 'company')->first();
        if ($sequence) {
            $isDeleted = true;
        } else {
            $isDeleted = false;
            // number
            $sequence = Sequence::where('name', 'company')->first();
            if (!$sequence) {
                $sequence = Sequence::create([
                    'name' => 'company',
                ]);
            }
        }


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


        $old = Year::where('year', $input['year'])->where('company_id', $company->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['company_id'] = $company->id;
        $year = Year::create($input);

        return $this->sendResponse(
            Year::find($year->id),
            "year created successfully",
            ApiCode::CREATED,
            0
        );
    }
    public function resetCompanySequence(Request $request)
    {
        $sequence = Sequence::where('name', 'company')->first();
        if (!$sequence) {
            $sequence = Sequence::create([
                'name' => 'company',
            ]);
        } else {
            $sequence->sequence = 0;
            $sequence->save();
        }
        DeletedSequence::where('name',  'company')->delete();
        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('company_id', $year->company_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' => 'company',
                'sequence' => $year->number
            ]);
        $year->delete();

        return $this->sendResponse(
            null,
            "year deleted successfully",
            ApiCode::SUCCESS,
            0
        );
    }

    public function delete($id)
    {
        $old = Company::findOrFail($id);
        DeletedSequence::create([
            'name' => 'company_id',
            'sequence' => $old->id
        ]);
        $old->delete();

        return $this->sendResponse(
            null,
            "company deleted successfully",
            ApiCode::SUCCESS,
            0
        );
    }
}
