<?php

namespace App\Http\Controllers\Pages;

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

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

class AccountController 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 = 'Account';
        $page_description = 'This is Account test page';
        $page_breadcrumbs = [
            ['page' => 'accounts', 'title' => 'Master Data'],
            ['page' => 'accounts', 'title' => 'Accounts']
        ];
        return view('pages.account.index', compact('page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $branch = Branch::all();
        $bank = Bank::all();
        $type = DB::table('bank_types')->get();
        return view('pages.account.create', compact('branch', 'bank', 'type'));
    }

    /**
     * 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|max:255',
            'idbank' => 'required|max:255',
            'accname' => 'required|max:255',
            'accno' => 'required|max:255',
            'acctype' => 'required',
            'isactive' => 'required',
        ]);
        if ($validator->fails()) {
            Alert::warning('Oops!', 'Something When Wrong!');
            return redirect('accounts')->withErrors($validator);
        } else {
            $id = IdGenerator::generate(['table' => 'accounts', 'field' => 'idacc', 'length' => 6, 'prefix' => 'ACC']);
            Account::create([
                'idacc' => $id,
                'idbranch' => $request->idbranch,
                'idbank' => $request->idbank,
                'accname' => strtoupper($request->accname),
                'accno' => $request->accno,
                'acctype' => $request->acctype,
                'isactive' => $request->isactive,
            ]);

            $idblc = IdGenerator::generate(['table' => 'balances', 'field' => 'idblc', 'length' => 13, 'prefix' => 'BLC' . date('ym')]);
            Balance::create([
                'idblc' => $idblc,
                'idacc' => $id,
                'dtopening' => date('Y-m-d'),
                'opening' => str_replace(',', '', $request->opening),
                'running' => str_replace(',', '', $request->opening),
                'closing' => 0,
                'iduser' => Auth::user()->iduser,
            ]);
            Helper::Activity('accounts', $id, 'CREATE');
            Alert::success('Success!', 'Data Has Been Saved!');
            return redirect('accounts');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\account  $account
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // $accounts = Account::select(['idacc', 'idbranch', 'idbank', 'accname', 'accno', 'accuser', 'accpwd', 'isactive', 'created_at']);
        $accounts = DB::table('accounts')
            ->join('branches', 'accounts.idbranch', '=', 'branches.idbranch')
            ->join('banks', 'accounts.idbank', '=', 'banks.idbank')
            ->select('accounts.idacc', 'branches.branchname', 'banks.bankcode', 'accounts.accname', 'accounts.accno', 'accounts.acctype', 'accounts.accuser', 'accounts.accpwd', 'accounts.isactive', 'accounts.created_at', 'accounts.updated_at')
            ->get();
        $i = 0;
        $array = array();
        foreach ($accounts as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'branch' => $data->branchname,
                'bank' => $data->bankcode,
                'accname' => $data->accname,
                'accno' => $data->accno,
                'acctype' => $data->acctype,
                'accuser' => $data->accuser,
                'accpwd' => $data->accpwd,
                'isactive' => $data->isactive,
                'created_at' => $data->created_at,
                'updated_at' => $data->updated_at,
                'idacc' => $data->idacc,
            );
        }
        return Datatables::of($array)->make(true);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\account  $account
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $branch = Branch::all();
        $bank = Bank::all();
        $type = DB::table('bank_types')->get();
        $data = Account::find($id);
        return view('pages.account.edit', compact('branch', 'bank', 'type', 'data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\account  $account
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $account = Account::find($id)
            ->update([
                'idbranch' => $request->idbranch,
                'idbank' => $request->idbank,
                'accname' => $request->accname,
                'accno' => $request->accno,
                'acctype' => $request->acctype,
                'accuser' => $request->accuser,
                'accpwd' => $request->accpwd,
                'isactive' => $request->isactive,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        Helper::Activity('accounts', $id, 'UDPATE');
        Alert::success('Success!', 'Data has been update!');
        return redirect('accounts');
    }

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

    public function addformat(Request $request)
    {
        $branch = Branch::all();
        $bank = Bank::all();
        $type = DB::table('bank_types')->get();
        return view('pages.account.format', compact('branch', 'bank', 'type'));
    }

    public function saveformat(Request $request)
    {
        list($bank, $type, $accname, $accno) = explode(',', $request->accformat);
        $idbank = Bank::where('bankcode', '=', $bank)->get()[0]->idbank;
        $validator = Validator::make($request->all(), [
            'idbranch' => 'required',
            'accformat' => 'required',
        ]);
        if ($validator->fails()) {
            Alert::warning('Oops!', 'Something When Wrong!');
            return redirect('accounts')->withErrors($validator);
        } else {
            if ($idbank == '') {
                Alert::warning('Oops!', 'Bank Code Not Found!');
            } else {
                $id = IdGenerator::generate(['table' => 'accounts', 'field' => 'idacc', 'length' => 6, 'prefix' => 'ACC']);
                Account::create([
                    'idacc' => $id,
                    'idbranch' => $request->idbranch,
                    'idbank' => $idbank,
                    'accname' => strtoupper($accname),
                    'accno' => $accno,
                    'acctype' => $type,
                    'isactive' => 1,
                ]);
                Helper::Activity('accounts', $id, 'IMPORT FORMAT');
                Alert::success('Success!', 'Data Has Been Saved!');
                return redirect('accounts');
            }
        }
    }
}
