<?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\Plain;
use App\Models\Account;
use App\Models\Movement;
use Log;

class PlainController extends AppBaseController
{


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

    public function add(Request $request)
    {
        Log::error($request);
        $rules =
            [
                'year' => 'required',
                'accountant_year_id' => 'required',

                'date' => 'required',
                'movement' => 'required',
                'debtor_movement' => 'required'

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

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


        $input = $request->all();
        $input['user_id'] = auth()->user()->id;
        $input['sequence'] = $sequence->sequence;
        $plain = Plain::create($input);

        $movementData = json_decode($request->movement);
        foreach ($movementData as $movement) {
            if ($movement->amount > 0)
                $mov = Movement::create([
                    'plain_id' =>   $plain->id,
                    'accountant_year_id' => $request->accountant_year_id,
                    'year' => $request->year,
                    'rcd_type' => 4,
                    'is_debtor' => 0,
                    'account_id' =>  $movement->accountId,
                    'amount' =>   $movement->amount,
                    'account_gp_id' => ($movement->accountId > 62 && $movement->accountId < 70) ? 62 : $movement->accountId,

                ]);
        }

        $debtor_movementData = json_decode($request->debtor_movement);
        foreach ($debtor_movementData as $debtor_movement) {
            if ($debtor_movement->amount > 0)
                $debtor_mov = Movement::create([
                    'plain_id' =>   $plain->id,
                    'accountant_year_id' => $request->accountant_year_id,
                    'year' => $request->year,
                    'rcd_type' => 4,
                    'is_debtor' => 1,
                    'account_id' => $debtor_movement->accountId,
                    'amount' =>  $debtor_movement->amount,
                    'account_gp_id' => ($debtor_movement->accountId > 62 && $debtor_movement->accountId < 70) ? 62 : $debtor_movement->accountId,

                ]);
        }


        return $this->sendResponse(
            [Plain::where('id', $plain->id)->first()],
            "plain created successfully",
            ApiCode::CREATED,
            0
        );
    }


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

        $plain = Plain::where('id', $id)->firstOrFail();

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

        $movementData = json_decode($request->movement);
        foreach ($movementData as $movement) {
            if ($movement->amount > 0)
                $mov = Movement::create([
                    'plain_id' =>   $plain->id,
                    'accountant_year_id' => $plain->accountant_year_id,
                    'year' => $plain->year,
                    'rcd_type' => 4,
                    'is_debtor' => 0,
                    'account_id' =>  $movement->accountId,
                    'amount' =>   $movement->amount,
                    'account_gp_id' => ($movement->accountId > 62 && $movement->accountId < 70) ? 62 : $movement->accountId,

                ]);
        }

        $debtor_movementData = json_decode($request->debtor_movement);
        foreach ($debtor_movementData as $debtor_movement) {
            if ($debtor_movement->amount > 0)
                $debtor_mov = Movement::create([
                    'plain_id' =>   $plain->id,
                    'accountant_year_id' => $plain->accountant_year_id,
                    'year' => $plain->year,
                    'rcd_type' => 4,
                    'is_debtor' => 1,
                    'account_id' =>  $debtor_movement->accountId,
                    'amount' =>   $debtor_movement->amount,
                    'account_gp_id' => ($debtor_movement->accountId > 62 && $debtor_movement->accountId < 70) ? 62 : $debtor_movement->accountId,

                ]);
        }


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

        if ($request->has('date'))
            if ($request->date != null) {
                $plain->date = $request->date;
            }

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

        $plain->save();
        return $this->sendResponse(
            [Plain::where('id', $plain->id)->first()],
            "rent updated successfully",
            ApiCode::SUCCESS,
            0
        );
    }
    public function all(Request $request)
    {


        if ($request->query("year") == null || $request->query("accountant_year_id") == null) {
            return $this->sendResponse(
                null,
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        $plains =  Plain::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("to") != null) {

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

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

            )->orderBy('created_at', 'DESC')
            ->get();


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