<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Validator;
use App\Responses;
use App\Helper;
use App\Models\Dana;

class DanaController extends Controller
{
	/**
	 * View
	 */

	public function view_dana(Request $req)
	{
		$data = [
			'dana' => Dana::getDanaById(Dana::PK_ID)[0],
		];

    $data['dana']->amt = number_format($data['dana']->amt, 0, ',', '.');

		return view('menu_v2.Finance._dana', $data);
	}


	/**
	 * API
	 */

	public function api_edit_dana(Request $req, $dana_id)
	{
		try {
			$now = time();

			$input = [
        'dana_id' => $dana_id,
				'saldo' => $req->amt,
			];
			$rulesInput = [
        'dana_id' => 'required|integer|not_in:0',
				'saldo' => 'required|numeric',
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}

			$dana = Dana::getDanaById(Dana::PK_ID);
			if (count($dana) < 1) {
				$apiResp = Responses::not_found('Dana not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}

      if ($input['saldo'] < Dana::MINIMUM_AMT) {
        $apiResp = Responses::bad_request('Minimum saldo dana Rp'.number_format(Dana::MINIMUM_AMT, 0, ',', '.'));
				return (new Response($apiResp, $apiResp['meta']['code']));
      }

			DB::beginTransaction();

			$updtDana = [
				'amt' => $input['saldo'],
			];
			Dana::updateDana($input['dana_id'], $updtDana);

			$apiResp = Responses::success('success update dana');

			DB::commit();
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}
}
