<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DeletedSequence;
use App\Models\Sequence;
use App\Models\DiwanRecord;
use App\ApiCode;

use Illuminate\Support\Str;
use Validator;
use App\Http\Controllers\AppBaseController;

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

    public function add(Request $request)
    {
        $rules =
            [
                'accountant_year_id' => 'required',
                'year' => 'required',
                'date' => 'required',
                'type' => 'required',
                'sender' => 'required',
                'conclusion' => 'required',
                'location' => 'required',
                'number' => 'required',
            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        $name = "diwan" . $request->type;
        $isDeleted = true;
        $sequence = DeletedSequence::where('name', $name)
            ->where('accountant_year_id', $request->accountant_year_id)
            ->where('year', $request->year)
            ->first();
        if (!$sequence) {
            $isDeleted = false;
            $sequence = Sequence::where('name', $name)
                ->where('accountant_year_id', $request->accountant_year_id)
                ->where('year', $request->year)
                ->first();
            if (!$sequence) {
                $sequence = Sequence::create([
                    'name' => $name,
                    '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();
        $diwan = DiwanRecord::create($input);

        if ($request->has('image')) {
            $uuid = Str::uuid();
            $diwan->addMediaFromRequest('image')->usingName($uuid)->usingFileName($uuid . '.' . $request->image->extension())->toMediaCollection('images');
            $diwan->save();
            //Log::error($request->file);
        }
        return $this->sendResponse(
            [DiwanRecord::where('id', $diwan->id)->first()],
            "receive created successfully",
            ApiCode::CREATED,
            0
        );
    }

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

        $diwan = DiwanRecord::where('id', $id)->firstOrFail();
        if ($request->has('date'))
            if ($request->date != null) {
                $diwan->date = $request->date;
            }
        if ($request->has('type'))
            if ($request->type != null) {
                $diwan->type = $request->type;
            }
        if ($request->has('sender'))
            if ($request->sender != null) {
                $diwan->sender = $request->sender;
            }
        if ($request->has('conclusion'))
            if ($request->conclusion != null) {
                $diwan->conclusion = $request->conclusion;
            }
        if ($request->has('location'))
            if ($request->location != null) {
                $diwan->location = $request->location;
            }
        if ($request->has('param1'))
            if ($request->param1 != null) {
                $diwan->param1 = $request->param1;
            }
        if ($request->has('param2'))
            if ($request->param2 != null) {
                $diwan->param2 = $request->param2;
            }
        if ($request->has('param3'))
            if ($request->param3 != null) {
                $diwan->param3 = $request->param3;
            }

        if ($request->has('image')) {
            $diwan->media->each->delete();
            $diwan->save();
            $uuid = Str::uuid();
            $diwan->addMediaFromRequest('image')->usingName($uuid)->usingFileName($uuid . '.' . $request->image->extension())->toMediaCollection('images');
        }
        $diwan->save();
        return $this->sendResponse(
            [DiwanRecord::where('id', $diwan->id)->first()],
            "pay updated successfully",
            ApiCode::SUCCESS,
            0
        );
    }

    public function all(Request $request)
    {
        $limit = 10;
        if ($request->query("limit") != null) {
            $limit = $request->query("limit");
        }
        if ($request->query("year") == null || $request->query("accountant_year_id") == null) {
            return $this->sendResponse(
                null,
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        $diwans =  DiwanRecord::with(['user' => function ($query) {
            $query->select('id', 'username');
        }])->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("number") != null) {
                        $number = $request->query("number");
                        return $query->where('number', 'like', '%' . $number . '%');
                    }
                }

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

            )
            ->where(
                function ($query) use ($request) {
                    if ($request->query("date") != null) {
                        $to = $request->query("date");
                        $to =  str_replace('/', '-', $to);
                        return $query->whereDate('date',  date("Y-m-d", strtotime($to)));
                    }
                }

            )->where(
                function ($query) use ($request) {
                    if ($request->query("type") != null) {
                        $type = $request->query("type");
                        return $query->where('type', $type);
                    }
                }

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

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

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

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

    public function delete($id, Request $request)
    {
        $diwan = DiwanRecord::where('id', $id)->firstOrFail();

        $year = $diwan->year;
        $accountant_year_id = $diwan->accountant_year_id;
        $seq = $diwan->sequence;

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