<?php

namespace App\Http\Controllers\Pages;

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

use App\Models\{Transaction, Branch, Product};

class TransactionController 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 = 'deposit';
        $page_title = 'Add Deposit';
        $page_description = 'This is Add Transaction page';
        $page_breadcrumbs = [
            ['page' => 'add-transaction', 'title' => 'Transaction'],
            ['page' => 'add-transaction', 'title' => 'Deposit']
        ];
        $branches = Branch::all();
        return view("pages.transaction.index", compact('branches', 'page', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    public function withdrawal()
    {
        $page = 'withdrawal';
        $page_title = 'Add Withdrawal';
        $page_description = 'This is Add Transaction page';
        $page_breadcrumbs = [
            ['page' => 'add-transaction', 'title' => 'Transaction'],
            ['page' => 'add-transaction', 'title' => 'Withdrawal']
        ];
        $branches = Branch::all();
        return view("pages.transaction.index", compact('branches', 'page', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    public function transfer()
    {
        $page = 'transfer';
        $page_title = 'Add Transfer';
        $page_description = 'This is Add Transaction page';
        $page_breadcrumbs = [
            ['page' => 'add-transaction', 'title' => 'Transaction'],
            ['page' => 'add-transaction', 'title' => 'Transfer']
        ];
        $branches = Branch::all();
        $idtrf = IdGenerator::generate(['table' => 'transactions', 'field' => 'note', 'length' => 13, 'prefix' => 'TRF' . date('m')]);
        return view("pages.transaction.index", compact('branches', 'page', 'page_title', 'page_description', 'page_breadcrumbs', 'idtrf'));
    }

    public function bonus()
    {
        $page = 'bonus';
        $page_title = 'Add Bonus';
        $page_description = 'This is Add Transaction page';
        $page_breadcrumbs = [
            ['page' => 'add-transaction', 'title' => 'Transaction'],
            ['page' => 'add-transaction', 'title' => 'Bonus']
        ];
        $branches = Branch::all();
        return view("pages.transaction.index", compact('branches', 'page', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    public function other()
    {
        $page = 'other';
        $page_title = 'Add Other Transaction';
        $page_description = 'This is Add Other Transaction page';
        $page_breadcrumbs = [
            ['page' => 'add-transaction', 'title' => 'Transaction'],
            ['page' => 'add-transaction', 'title' => 'Other']
        ];
        $branches = Branch::all();
        return view("pages.transaction.index", compact('branches', 'page', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    public function pending()
    {
        $page = 'pending';
        $page_title = 'View Pending Transaction';
        $page_description = 'This is View Pending Transaction';
        $page_breadcrumbs = [
            ['page' => 'add-transaction', 'title' => 'Transaction'],
            ['page' => 'add-transaction', 'title' => 'Pending']
        ];
        $branches = Branch::all();
        return view("pages.transaction.index", compact('branches', 'page', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    public function getProducts(Request $request)
    {
        $id = $request->idbranch;
        $products = Product::where('idbranch', $id)->get();
        return $products;
    }

    public function getAccounts(Request $request)
    {
        $res = '';
        $id = $request->idbranch;
        $type = $request->type;
        $accounts = DB::table('accounts')
            ->join('banks', 'accounts.idbank', '=', 'banks.idbank')
            ->select('accounts.*', 'banks.bankcode');
        if ($type == 'deposit' || $type == 'withdrawal') {
            $res = $accounts->where('accounts.idbranch', '=', $id)
                ->where('accounts.isactive', '=', 1)
                ->where(function ($where) use ($type) {
                    $where->orWhere('accounts.acctype', '=', 'BOTH')
                        ->orWhere('accounts.acctype', '=', $type);
                })
                ->get();
        } else if ($type == 'bonus') {
            $res = $accounts->where('accounts.idbranch', '=', $id)
                ->where('accounts.isactive', '=', 1)
                ->where(function ($where) use ($type) {
                    $where->orWhere('accounts.acctype', '=', 'BOTH')
                        ->orWhere('accounts.acctype', '=', 'WITHDRAWAL');
                })
                ->get();
        } else {
            $res = $accounts->where('accounts.idbranch', '=', $id)
                ->where('accounts.isactive', '=', 1)
                ->get();
        }
        $res = $accounts->get();

        $i = 0;
        $array = array();
        foreach ($res as $data) {
            $i++;
            $balance = @Helper::checkBalance($data->idacc, 'running');
            $array[] = array(
                'idacc' => $data->idacc,
                'bankcode' => $data->bankcode,
                'accname' => $data->accname,
                'accno' => $data->accno,
                'balance' => number_format($balance)
            );
        }
        return $array;
    }

    public function popupmember()
    {
        return view('popup.member');
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $iduser = Auth::user()->iduser;
        $validator = Validator::make($request->all(), [
            'idbranch' => 'required',
            'datetrc' => 'required',
            // 'idacc' => 'required',
            'trctype' => 'required',
            'amount' => 'required',
        ]);
        if ($validator->fails()) {
            Alert::warning('Oops!', 'Something When Wrong!');
            if ($request->trctype == "DEPOSIT") {
                return redirect('transaction')->withErrors($validator);
            } else if ($request->trctype == "WITHDRAWAL") {
                return redirect('transaction/withdrawal')->withErrors($validator);
            } else if ($request->trctype == "TRANSFER") {
                return redirect('transaction/transfer')->withErrors($validator);
            } else if ($request->trctype == "BONUS") {
                return redirect('transaction/bonus')->withErrors($validator);
            } else if ($request->trctype == "OTHER") {
                return redirect('transaction/other')->withErrors($validator);
            }
        } else {
            $id = IdGenerator::generate(['table' => 'transactions', 'field' => 'idtrc', 'length' => 13, 'prefix' => 'TRC' . date('m')]);
            // DEPOSIT TRANSACTION
            if ($request->trctype == "DEPOSIT") {
                $coin = @Helper::runCoin($request->idbranch, '2021-01-01', date('Y-m-d'));
                $getcoin = str_replace(',', '', $request->amount) * $request->coin;
                if ($coin <= 0) {
                    Alert::success('Oops!', 'Not Enough Coin');
                    return redirect('transaction');
                } else {
                    if ($request->trcstatus == 'CONFIRM') {
                        $dtconfirm = date('Y-m-d H:i:s');
                        Helper::addBalance($request->idacc, str_replace(',', '', $request->amount));
                        Helper::rdcCoin($request->idbranch, str_replace(',', '', $getcoin));
                    } else {
                        $dtconfirm = null;
                    }
                    $affected = Transaction::create([
                        'idtrc' => $id,
                        'idbranch' => $request->idbranch,
                        'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                        'idmember' => $request->idmember,
                        'idacc' => $request->idacc,
                        'dttype' => 'DB',
                        'trctype' => $request->trctype,
                        'amount' => str_replace(',', '', $request->amount),
                        'coin' => str_replace(',', '', $getcoin),
                        'trcstatus' => $request->trcstatus,
                        'dateconfirm' => $dtconfirm,
                        'remark' => $request->remark,
                        'iduser' => $iduser,
                    ]);
                    if ($affected) {
                        Helper::Activity('transaction', $id, 'CREATE DEPOSIT');
                        Alert::success('Success!', 'Data Has Been Saved!');
                        return redirect('transaction');
                    } else {
                        Alert::success('Error!', 'Something When Wrong!');
                        return redirect('transaction');
                    }
                }
            }
            // WITHDRAWAL TRANSACTION
            else if ($request->trctype == "WITHDRAWAL") {
                if ($request->trcstatus == 'CONFIRM') {
                    $dtconfirm = date('Y-m-d H:i:s');
                    Helper::rdcBalance($request->idacc, str_replace(',', '', $request->amount), str_replace(',', '', $request->fee));
                    Helper::addCoin($request->idbranch, str_replace(',', '', $request->amount));
                } else {
                    $dtconfirm = null;
                }
                $affected = Transaction::create([
                    'idtrc' => $id,
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idmember' => $request->idmember,
                    'idacc' => $request->idacc,
                    'dttype' => 'CR',
                    'trctype' => $request->trctype,
                    'amount' => str_replace(',', '', $request->amount),
                    'coin' => str_replace(',', '', $request->amount),
                    'fee' => str_replace(',', '', $request->fee),
                    'trcstatus' => $request->trcstatus,
                    'dateconfirm' => $dtconfirm,
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                ]);
                if ($affected) {
                    Helper::Activity('transaction', $id, 'CREATE WITHDRAWAL');
                    Alert::success('Success!', 'Data Has Been Saved!');
                    return redirect('transaction/withdrawal');
                } else {
                    Alert::success('Error!', 'Something When Wrong!');
                    return redirect('transaction/withdrawal');
                }
            }
            // TRANSFER TRANSACTION
            else if ($request->trctype == "TRANSFER") {
                if ($request->trcstatus == 'CONFIRM') {
                    $dtconfirm = date('Y-m-d H:i:s');
                    Helper::rdcBalance($request->fromacc, str_replace(',', '', $request->amount), str_replace(',', '', $request->fee));
                    Helper::addBalance($request->toacc, str_replace(',', '', $request->amount));
                } else {
                    $dtconfirm = null;
                }
                $trfout = Transaction::create([
                    'idtrc' => IdGenerator::generate(['table' => 'transactions', 'field' => 'idtrc', 'length' => 13, 'prefix' => 'TRC' . date('m')]),
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idacc' => $request->fromacc,
                    'dttype' => 'CR',
                    'trctype' => $request->trctype,
                    'amount' => str_replace(',', '', $request->amount),
                    'fee' => str_replace(',', '', $request->fee),
                    'note' => $request->idtrf,
                    'trcstatus' => $request->trcstatus,
                    'dateconfirm' => $dtconfirm,
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                ]);
                $trfin = Transaction::create([
                    'idtrc' => IdGenerator::generate(['table' => 'transactions', 'field' => 'idtrc', 'length' => 13, 'prefix' => 'TRC' . date('m')]),
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idacc' => $request->toacc,
                    'dttype' => 'DB',
                    'trctype' => $request->trctype,
                    'amount' => str_replace(',', '', $request->amount),
                    'note' => $request->idtrf,
                    'trcstatus' => $request->trcstatus,
                    'dateconfirm' => $dtconfirm,
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                ]);
                if ($trfout && $trfin) {
                    Helper::Activity('transaction', $request->idtrf, 'CREATE TRANSFER');
                    Alert::success('Success!', 'Data Has Been Saved!');
                    return redirect('transaction/transfer');
                } else {
                    Alert::warning('Error!', 'Something When Wrong!');
                    return redirect('transaction/transfer');
                }
            }
            // BONUS TRANSACTION
            else if ($request->trctype == "BONUS") {
                if ($request->trcstatus == 'CONFIRM') {
                    $dtconfirm = date('Y-m-d H:i:s');
                    Helper::rdcCoin($request->idbranch, str_replace(',', '', $request->amount));
                } else {
                    $dtconfirm = null;
                }
                $affected = Transaction::create([
                    'idtrc' => $id,
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idmember' => $request->idmember,
                    'dttype' => '-',
                    'trctype' => $request->trctype,
                    'amount' => 0,
                    'coin' => str_replace(',', '', $request->amount),
                    'trcstatus' => $request->trcstatus,
                    'dateconfirm' => $dtconfirm,
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                ]);
                if ($affected) {
                    Helper::Activity('transaction', $id, 'CREATE BONUS');
                    Alert::success('Success!', 'Data Has Been Saved!');
                    return redirect('transaction/bonus');
                } else {
                    Alert::success('Error!', 'Something When Wrong!');
                    return redirect('transaction/bonus');
                }
            }
            // OTHER TRANSACTION
            else if ($request->trctype == "OTHER") {
                if ($request->trcstatus == 'CONFIRM') {
                    $dtconfirm = date('Y-m-d H:i:s');
                    if ($request->dttype == 'DB') {
                        Helper::addBalance($request->idacc, str_replace(',', '', $request->amount));
                    } else {
                        Helper::rdcBalance($request->idacc, str_replace(',', '', $request->amount), str_replace(',', '', 0));
                    }
                } else {
                    $dtconfirm = null;
                }
                $affected = Transaction::create([
                    'idtrc' => $id,
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idmember' => $request->idmember,
                    'idacc' => $request->idacc,
                    'dttype' => $request->dttype,
                    'trctype' => $request->trctype,
                    'amount' => str_replace(',', '', $request->amount),
                    'trcstatus' => $request->trcstatus,
                    'dateconfirm' => $dtconfirm,
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                ]);
                if ($affected) {
                    Helper::Activity('transaction', $id, 'CREATE OTHER');
                    Alert::success('Success!', 'Data Has Been Saved!');
                    return redirect('transaction/other');
                } else {
                    Alert::success('Error!', 'Something When Wrong!');
                    return redirect('transaction/other');
                }
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Transaction  $transaction
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, $id)
    {
        $tanggal = date('Y-m-d');
        if ($request->type == "bonus") {

            $res = $transaction = DB::table('transactions')
                ->join('branches', 'branches.idbranch', '=', 'transactions.idbranch')
                ->leftjoin('members', 'members.idmember', '=', 'transactions.idmember')
                ->leftjoin('products', 'products.idproduct', '=', 'transactions.idproduct')
                ->join('users', 'users.iduser', '=', 'transactions.iduser')
                ->select('transactions.*', 'branches.branchname', 'members.mbraccname', 'products.productname', 'users.username')
                ->whereBetween(DB::raw('LEFT(transactions.datetrc,10)'), [$tanggal, $tanggal])
                ->where('transactions.trctype', '=', $request->type);

            if ($request->mbr != '') {
                $res = $transaction->where('transactions.idmember', '=', $request->mbr)
                    ->orderByDesc('transactions.datetrc')
                    ->get();
            } else {
                $res = $transaction->orderByDesc('transactions.datetrc')
                    ->get();
            }

            $i = 0;
            $array = array();
            foreach ($res as $data) {
                $i++;
                $array[] = array(
                    'no' => $i,
                    'branch' => $data->branchname,
                    'datetrc' => $data->datetrc,
                    'member' => $data->mbraccname,
                    'product' => $data->productname,
                    'account' => null,
                    'trctype' => $data->trctype,
                    'amount' => number_format($data->amount),
                    'trcstatus' => $data->trcstatus,
                    'dateconfirm' => $data->dateconfirm,
                    'user' => $data->username,
                    'created_at' => $data->created_at
                );
            }
        } else {

            $res = $transaction = DB::table('transactions')
                ->join('branches', 'branches.idbranch', '=', 'transactions.idbranch')
                ->join('accounts', 'accounts.idacc', '=', 'transactions.idacc')
                ->leftjoin('members', 'members.idmember', '=', 'transactions.idmember')
                ->leftjoin('products', 'products.idproduct', '=', 'transactions.idproduct')
                ->join('users', 'users.iduser', '=', 'transactions.iduser')
                ->select('transactions.*', 'branches.branchname', 'members.mbraccname', 'products.productname', 'accounts.accname', 'users.username')
                ->whereBetween(DB::raw('LEFT(transactions.datetrc,10)'), [$tanggal, $tanggal])
                ->where('transactions.trctype', '=', $request->type);

            if ($request->mbr != '') {
                $res = $transaction->where('transactions.idmember', '=', $request->mbr)
                    ->orderByDesc('transactions.datetrc')
                    ->get();
            } else {
                $res = $transaction->orderByDesc('transactions.datetrc')
                    ->get();
            }

            $i = 0;
            $array = array();
            foreach ($res as $data) {
                $i++;
                $array[] = array(
                    'no' => $i,
                    'branch' => $data->branchname,
                    'datetrc' => $data->datetrc,
                    'member' => $data->mbraccname,
                    'product' => $data->productname,
                    'account' => $data->accname,
                    'trctype' => $data->trctype,
                    'amount' => number_format($data->amount),
                    'trcstatus' => $data->trcstatus,
                    'dateconfirm' => $data->dateconfirm,
                    'user' => $data->username,
                    'created_at' => $data->created_at
                );
            }
        }
        return Datatables::of($array)->make(true);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Transaction  $transaction
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Transaction  $transaction
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Transaction  $transaction
     * @return \Illuminate\Http\Response
     */
    public function destroy(Transaction $transaction)
    {
        //
    }
}