<?php

namespace App\Http\Controllers;

use App\Http\Controllers\AppBaseController;
use Illuminate\Http\Request;
use App\ApiCode;
use Validator;
use App\Models\Sequence;
use App\Models\DeletedSequence;
use App\Models\Pay;
use App\Models\Rent;
use App\Models\Deposit;
use App\Models\Plain;
use App\Models\GrantPerson;
use App\Models\Movement;
use Log;

class PayController extends AppBaseController
{

    public function __construct()
    {
        $this->middleware('auth:api',);
    }
    public function add(Request $request)
    {

        /**
         *
         *
        'name',
        'condition',
        'date',
        'note',
        'account_id',
        'debtor_account_id',
        'check_num',
         */

        Log::error($request);
        $rules =
            [
                'year' => 'required',
                'accountant_year_id' => 'required',

                'name' => 'required',
                'date' => 'required',
                'debtor_account_id' => 'required',
                'account_id' => 'required',
                'total' => 'required',
                'movement' => 'required',

            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        $isDeleted = true;
        $sequence = DeletedSequence::where('name', 'pay')
            ->where('accountant_year_id', $request->accountant_year_id)
            ->where('year', $request->year)
            ->first();
        if (!$sequence) {
            $isDeleted = false;
            $sequence = Sequence::where('name', 'pay')
                ->where('accountant_year_id', $request->accountant_year_id)
                ->where('year', $request->year)
                ->first();
            if (!$sequence) {
                $sequence = Sequence::create([
                    'name' => 'pay',
                    'accountant_year_id' => $request->accountant_year_id,
                    'year' => $request->year
                ]);
            }

            $sequence->sequence += 1;
            $sequence->save();
        }

        $input = $request->all();
        $input['user_id'] = auth()->user()->id;
        $input['sequence'] = $sequence->sequence;
        if ($isDeleted) $sequence->delete();
        $pay = Pay::create($input);

        $movementData = json_decode($request->movement);
        //$movementData = $request->movement;
        $totalDiscount = 0;
        foreach ($movementData as $movement) {
            if ($movement->amount > 0)
                $mov = Movement::create([
                    'pay_id' =>   $pay->id,
                    'accountant_year_id' => $request->accountant_year_id,
                    'year' => $request->year,
                    'rcd_type' => 1,
                    'is_debtor' => 0,
                    'note' => isset($movement->note) ?  $movement->note : null,
                    'account_id' =>  $movement->accountId,
                    'amount' =>   $movement->amount,
                    'account_gp_id' => ($movement->accountId > 62 && $movement->accountId < 70) ? 62 : $movement->accountId,

                ]);
            $totalDiscount += $movement->amount;
        }

        $mov3 = Movement::create([
            'pay_id' =>   $pay->id,
            'accountant_year_id' => $request->accountant_year_id,
            'year' => $request->year,
            'rcd_type' => 1,
            'is_debtor' => 0,
            'account_id' =>  $request->account_id,
            'amount' =>   $request->total -  $totalDiscount,
            'account_gp_id' => $request->account_id,
        ]);
        $mov2 = Movement::create([
            'pay_id' =>   $pay->id,
            'accountant_year_id' => $pay->accountant_year_id,
            'year' => $pay->year,
            'rcd_type' => 1,
            'is_debtor' => 1,
            'account_id' =>  $request->debtor_account_id,
            'amount' =>   $request->total,
            'account_gp_id' => $request->debtor_account_id,
        ]);
        return $this->sendResponse(
            [Pay::where('id', $pay->id)->first()],
            "receive created successfully",
            ApiCode::CREATED,
            0
        );
    }
    public function delete($id, Request $request)
    {
        $pay = PAy::where('id', $id)->firstOrFail();

        foreach ($pay->movements as $old) {
            $old->delete();
        }


        $year = $pay->year;
        $accountant_year_id = $pay->accountant_year_id;
        $seq = $pay->sequence;
        DeletedSequence::create([
            'name' => 'pay',
            'accountant_year_id' => $accountant_year_id,
            'year' => $year,
            'sequence' => $seq,
        ]);
        $pay->delete();
        return $this->sendResponse(
            null,
            "pay deleted successfully",
            ApiCode::SUCCESS,
            0
        );
    }

    public function edit($id, Request $request)
    {
        $rules =
            [



                'debtor_account_id' => 'required',
                'account_id' => 'required',

                'total' => 'required',
                'movement' => 'required',

            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        $pay = Pay::where('id', $id)->firstOrFail();

        foreach ($pay->movements as $old) {
            $old->delete();
        }


        $movementData = json_decode($request->movement);
        //$movementData = $request->movement;
        $totalDiscount = 0;
        foreach ($movementData as $movement) {
            if ($movement->amount > 0)
                $mov = Movement::create([
                    'pay_id' =>   $pay->id,
                    'accountant_year_id' => $pay->accountant_year_id,
                    'year' => $pay->year,
                    'rcd_type' => 1,
                    'is_debtor' => 0,
                    'note' => isset($movement->note) ?  $movement->note : null,
                    'account_id' =>  $movement->accountId,
                    'amount' =>   $movement->amount,
                    'account_gp_id' => ($movement->accountId > 62 && $movement->accountId < 70) ? 62 : $movement->accountId,

                ]);
            $totalDiscount += $movement->amount;
        }

        $mov3 = Movement::create([
            'pay_id' =>   $pay->id,
            'accountant_year_id' => $pay->accountant_year_id,
            'year' => $pay->year,
            'rcd_type' => 1,
            'is_debtor' => 0,
            'account_id' =>  $request->account_id,
            'amount' =>   $request->total -  $totalDiscount,
            'account_gp_id' => $request->account_id,
        ]);
        $mov2 = Movement::create([
            'pay_id' =>   $pay->id,
            'accountant_year_id' => $pay->accountant_year_id,
            'year' => $pay->year,
            'rcd_type' => 1,
            'is_debtor' => 1,
            'account_id' =>  $request->debtor_account_id,
            'amount' =>   $request->total,
            'account_gp_id' => $request->debtor_account_id,
        ]);


        if ($request->has('status'))
            if ($request->status != null) {
                $pay->status = $request->status;
            }

        if ($request->has('account_id'))
            if ($request->account_id != null) {
                $pay->account_id = $request->account_id;
            }

        if ($request->has('date'))
            if ($request->date != null) {
                $pay->date = $request->date;
            }
        if ($request->has('name'))
            if ($request->name != null) {
                $pay->name = $request->name;
            }
        if ($request->has('condition'))
            if ($request->condition != null) {
                $pay->condition = $request->condition;
            }
        if ($request->has('check_num'))
            if ($request->check_num != null) {
                $pay->check_num = $request->check_num;
            }

        if ($request->has('note'))
            if ($request->note != null) {
                $pay->note = $request->note;
            }

        $pay->save();
        return $this->sendResponse(
            [Pay::where('id', $pay->id)->first()],
            "pay updated successfully",
            ApiCode::SUCCESS,
            0
        );
    }


    public function all(Request $request)
    {

        $limit = 10;
        $page = 1;
        if ($request->query("limit") != null) {
            $limit = $request->query("limit");
        }
        if ($request->query("page") != null) {
            $page = $request->query("page");
        }

        $offset = $page * $limit - $limit;
        if ($request->query("year") == null || $request->query("accountant_year_id") == null) {
            return $this->sendResponse(
                null,
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        $pays =  Pay::where('year', $request->query("year"))
            ->where('accountant_year_id', $request->query("accountant_year_id"))
            ->where(
                function ($query) use ($request) {
                    if ($request->query("sequence") != null) {
                        $sequence = $request->query("sequence");
                        return $query->where('sequence', $sequence);
                    }
                }

            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("name") != null) {
                        $query->whereHas(
                            'movements',
                            function ($query) use ($request) {
                                if ($request->query("name") != null) {
                                    $account_name = $request->query("name");
                                    return $query->whereHas('account', function ($query) use ($account_name) {
                                        $query->where('name',  'like', '%' . $account_name . '%');
                                    });
                                }
                            }
                        );
                    }
                }
            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("from") != null) {
                        $from = $request->query("from");
                        $from =  str_replace('/', '-', $from);

                        return $query->whereDate('date', '>=', date("Y-m-d", strtotime($from)));
                    }
                }

            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("search_rec_name") != null) {
                        $name = $request->query("search_rec_name");

                        return $query->where('name', 'like', '%' . $name . '%');
                    }
                }

            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("search_check") != null) {
                        $search_check = $request->query("search_check");

                        return $query->where('check_num', 'like', '%' . $search_check . '%');
                    }
                }

            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("condition") != null) {
                        $condition = $request->query("condition");

                        return $query->where('condition', 'like', '%' . $condition . '%');
                    }
                }

            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("to") != null) {

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

                        $to =  str_replace('/', '-', $to);
                        return $query->whereDate('date', '<=', date("Y-m-d", strtotime($to)));
                    }
                }

            )->orderBy('created_at', 'DESC')
            ->limit($limit)
            ->offset($offset)
            ->get();


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