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

class RentController extends AppBaseController
{

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


    public function add(Request $request)
    {

        $rules =
            [
                'year' => 'required',
                'accountant_year_id' => 'required',

                'name' => 'required',
                'statement' => 'required',
                'date' => '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', 'rent')
            ->where('accountant_year_id', $request->accountant_year_id)
            ->where('year', $request->year)
            ->first();
        if (!$sequence) {
            $sequence = Sequence::create([
                'name' => 'rent',
                '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;
        $rent = Rent::create($input);
        $total = 0;
        if ($request->has('rent_amount'))
            if ($request->rent_amount != null) {

                $rent_amount = $request->rent_amount;
                $total += $rent_amount;
                $movement = Movement::create([
                    'rent_id' =>   $rent->id,
                    'accountant_year_id' => $request->accountant_year_id,
                    'year' => $request->year,
                    'rcd_type' => 3,
                    'is_debtor' => 0,
                    'account_id' =>  78,
                    'amount' =>  $rent_amount,
                    'account_gp_id' => 78,

                ]);
            }
        if ($request->has('get_amount'))

            if ($request->get_amount != null) {

                $get_amount = $request->get_amount;
                $total += $get_amount;
                $movement2 = Movement::create([
                    'rent_id' =>   $rent->id,
                    'accountant_year_id' => $request->accountant_year_id,
                    'year' => $request->year,
                    'rcd_type' => 3,
                    'is_debtor' => 0,
                    'account_id' =>  7,
                    'amount' =>  $get_amount,
                    'account_gp_id' => 7,
                ]);
            }
        $movement3 = Movement::create([
            'rent_id' =>   $rent->id,
            'accountant_year_id' => $request->accountant_year_id,
            'year' => $request->year,
            'rcd_type' => 3,
            'is_debtor' => 1,
            'account_id' =>  48,
            'amount' =>  $total,
            'account_gp_id' => 48,
        ]);


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

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

        $rent = Rent::where('id', $id)->firstOrFail();
        if ($request->has('rent_amount') || $request->has('get_amount')) {
            $total = 0;

            if ($request->has('get_amount'))
                if ($request->get_amount != null) {
                    $exists = false;
                    foreach ($rent->movements as $movement) {
                        if ($movement->account_id == 7) {
                            $exists = true;
                            $total -= $movement->amount;
                            $movement->amount = $request->get_amount;
                            $movement->save();
                            $total += $movement->amount;
                            break;
                        }
                    }
                    if (!$exists) {
                        $movement2 = Movement::create([
                            'rent_id' =>   $rent->id,
                            'accountant_year_id' => $rent->accountant_year_id,
                            'year' => $rent->year,
                            'rcd_type' => 3,
                            'is_debtor' => 0,
                            'account_id' =>  7,
                            'amount' =>  $request->get_amount,
                            'account_gp_id' => 7,
                        ]);

                        $total += $movement2->amount;
                    }
                }
            if ($request->has('rent_amount'))
                if ($request->rent_amount != null) {
                    $exists = false;
                    foreach ($rent->movements as $movement) {
                        if ($movement->account_id == 78) {
                            $exists = true;
                            $total -= $movement->amount;
                            $movement->amount = $request->rent_amount;
                            $movement->save();
                            $total += $movement->amount;
                            break;
                        }
                    }
                    if (!$exists) {
                        $movement3 = Movement::create([
                            'rent_id' =>   $rent->id,
                            'accountant_year_id' => $rent->accountant_year_id,
                            'year' => $rent->year,
                            'rcd_type' => 3,
                            'is_debtor' => 0,
                            'account_id' => 78,
                            'amount' =>  $request->rent_amount,
                            'account_gp_id' => 78,
                        ]);

                        $total += $movement3->amount;
                    }
                }
            foreach ($rent->movements as $movement) {
                if ($movement->account_id == 48) {
                    $movement->amount += $total;
                    $movement->save();
                    break;
                }
            }
        }
        if ($request->has('status'))
            if ($request->status != null) {
                $rent->status = $request->status;
            }
        if ($request->has('name'))
            if ($request->name != null) {
                $rent->name = $request->name;
            }
        if ($request->has('date'))
            if ($request->date != null) {
                $rent->date = $request->date;
            }
        if ($request->has('statement'))
            if ($request->statement != null) {
                $rent->statement = $request->statement;
            }
        if ($request->has('note'))
            if ($request->note != null) {
                $rent->note = $request->note;
            }

        $rent->save();
        return $this->sendResponse(
            [Rent::where('id', $rent->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
            );
        }
        $rents =  Rent::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) {
                        $name = $request->query("name");
                        return $query->where('name', 'like', '%' . $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(
            $rents,
            "here are your rents!",
            ApiCode::SUCCESS,
            0
        );
    }
}
