<?php

namespace App\Http\Controllers;

use App\Http\Controllers\AppBaseController;
use Illuminate\Http\Request;
use App\ApiCode;
use App\Models\ReadyAccount;
use App\Models\Account;
use Validator;

class ReadyAccountController extends AppBaseController
{
    public function __construct()
    {
        $this->middleware('auth:api',);
    }
    public function all(Request $request)
    {
        $readyAccounts = ReadyAccount::where(function ($query) use ($request) {
            if ($request->query("id") != null) {
                $id = $request->query("id");
                return $query->where('id', $id);
            }
        })
            ->where(function ($query) use ($request) {
                if ($request->query("type") != null) {
                    $type = $request->query("type");
                    return $query->where('type', $type);
                }
            })
            ->orderBy('index')
            ->get();

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

    public function edit(Request $request)
    {

        $rules =
            [
                'accounts' => 'required',
                'type' => 'required',

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



        $accounts = json_decode($request->accounts);
        foreach ($accounts as $account) {
            if ($account->amount > 0)
                ReadyAccount::create([
                    'type' =>   $request->type,
                    'amount' => $account->amount,
                    'account_id' => $account->account_id,
                    'name' => $account->name,
                    'index' => $account->index,
                    'rcd_type' => 0,

                ]);
        }


        return $this->sendResponse(
            null,
            "ready account updated successfully",
            ApiCode::SUCCESS,
            0
        );
    }
}
