<?php

namespace App\Http\Controllers;

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

class AccountController extends AppBaseController
{

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

    public function all(Request $request)
    {
        $accounts =  Account::where(
            function ($query) use ($request) {
                if ($request->query("parent_id") != null) {
                    $parent_id = $request->query("parent_id");
                    return $query->where('parent_id', $parent_id);
                }
            }

        )->get();


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

    public function add(Request $request)
    {
        $rules =
            [
                'name' => 'required|unique:accounts',
            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }
        if ($request->has('parent_id'))
            if ($request->parent_id != null) {
                $parent = Account::where('id', $request->parent_id)->first();
                if (!$parent)
                    return $this->sendResponse(
                        null,
                        "error",
                        ApiCode::BAD_REQUEST,
                        1
                    );
            }
        $account = Account::create($request->all());
        return  $this->sendResponse(
            [$account],
            "here are your accounts!",
            ApiCode::CREATED,
            0
        );
    }
}
