<?php

namespace App\Http\Controllers\Pages;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Support\Facades\Auth;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\DB;

use App\Models\{Account, Balance, Branch};

class BalanceController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $page_title = 'Balance';
        $page_description = 'This is Balance Page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Balance'],
            ['page' => 'balance', 'title' => 'Balance Bank']
        ];
        return view('pages.balance.index', compact('page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $page_title = 'Add Balance';
        $page_description = 'This is Add Balance Page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Balance'],
            ['page' => 'balance', 'title' => 'Add Balance Bank']
        ];
        $branch = Branch::all();
        return view('pages.balance.create', compact('branch', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'idbranch' => 'required',
            'idacc' => 'required',
            'datetrc' => 'required',
            'opening' => 'required'
        ]);
        if ($validator->fails()) {
            Alert::warning('Oops!', 'Something When Wrong!');
            return redirect('balances')->withErrors($validator);
        } else {
            $id = IdGenerator::generate(['table' => 'balances', 'field' => 'idblc', 'length' => 13, 'prefix' => 'BLC' . date('ym')]);
            $affected = Balance::create([
                'idblc' => $id,
                'idacc' => $request->idacc,
                'dtopening' => $request->datetrc,
                'opening' => str_replace(',', '', $request->opening),
                'running' => str_replace(',', '', $request->opening),
                'closing' => 0,
                'iduser' => Auth::user()->iduser,
            ]);
            if ($affected) {
                Helper::Activity('balances', $id, 'CREATE');
                Alert::success('Success!', 'Data Has Been Saved!');
                return redirect('balances');
            } else {
                Alert::success('Error!', 'Something When Wrong!');
                return redirect('balances');
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Balance  $balance
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        $res = '';
        $query = $request->qr;
        $dtfrom = $request->df;
        $dtto = $request->dt;

        $result = DB::table('balances')
            ->join('accounts', 'balances.idacc', '=', 'accounts.idacc')
            ->join('branches', 'accounts.idbranch', '=', 'branches.idbranch')
            ->join('banks', 'accounts.idbank', '=', 'banks.idbank')
            ->join('users', 'balances.iduser', '=', 'users.iduser')
            ->select('balances.*', 'branches.branchname', 'accounts.accname', 'accounts.accno', 'banks.bankcode', 'banks.bankname', 'users.username')
            ->orderByDesc('balances.created_at');

        if ($query != '') {
            $res = $result->orWhere('branches.branchname', 'LIKE', '%' . $query . '%')
                ->orWhere('accounts.accname', 'LIKE', '%' . $query . '%')
                ->orWhere('accounts.accno', 'LIKE', '%' . $query . '%')
                ->orWhere('banks.bankcode', 'LIKE', '%' . $query . '%')
                ->orWhere('banks.bankname', 'LIKE', '%' . $query . '%')
                ->get();
        }
        if ($dtfrom != '' && $dtto != '') {
            $res = $result->whereBetween('balances.dtopening', [$dtfrom, $dtto])
                ->get();
        }

        $i = 0;
        $array = array();
        foreach ($res as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'branch' => $data->branchname,
                'account' => $data->bankcode . ' | ' . $data->accname . ' - ' . $data->accno,
                'dtopening' => $data->dtopening,
                'opening' => number_format($data->opening),
                'running' => number_format(@Helper::runBalance($data->idacc, $dtfrom, $dtto)),
                'dtclosing' => $data->dtclosing,
                'closing' => number_format($data->closing),
                'created_at' => $data->created_at,
                'user' => strtoupper($data->username),
                'idblc' => $data->idblc,
            );
        }
        return Datatables::of($array)->make(true);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Balance  $balance
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $page_title = 'Edit Balance';
        $page_description = 'This is Edit Balance Page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Balance'],
            ['page' => 'balance', 'title' => 'Edit Balance Bank']
        ];
        $branch = Branch::all();
        $account = Account::all();
        $balance = Balance::find($id);
        return view('pages.balance.edit', compact('balance', 'branch', 'account', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Balance  $balance
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $affected = Balance::find($id)
            ->update([
                'dtopening' => $request->dtopening,
                'opening' => str_replace(',', '', $request->opening),
                'running' => str_replace(',', '', $request->opening),
                'dtclosing' => $request->dtclosing,
                'closing' => str_replace(',', '', $request->closing),
                'remark' => $request->remark,
                'iduser' => Auth::user()->iduser,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        if ($affected) {
            Helper::Activity('balances', $id, 'UPDATE');
            Alert::success('Success!', 'Data has been update!');
            return redirect('balances');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Balance  $balance
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Helper::Activity('balances', $id, 'DELETE');
        Balance::find($id)->delete();
    }
}
