<?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 Illuminate\Support\Facades\Auth;
use App\Models\{Transaction, Branch, Product, Member, Account};
use RealRashid\SweetAlert\Facades\Alert;

use App\Helpers\Helper;

class HistoryController 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 = 'History Transactions';
        $page_description = 'This is History Transaction test page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Transactions'],
            ['page' => 'users', 'title' => 'History Transactions']
        ];
        $branches = Branch::all();
        return view('pages.history.index', compact('branches', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * 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)
    {
        //
    }

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

        if ($page == 'members') {
            $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')
                ->join('accounts', 'accounts.idacc', '=', 'transactions.idacc')
                ->join('banks', 'banks.idbank', '=', 'accounts.idbank')
                ->select('transactions.*', 'members.username AS mbruser', 'accounts.accname', 'banks.bankcode', 'products.productname', 'branches.branchname', 'users.username');

            if ($query != '') {
                $res = $transaction->where('members.idmember', '=', $query)
                    ->where('transactions.trcstatus', '=', 'CONFIRM')
                    ->get();
            }
            if ($dtfrom != '' && $dtto != '') {
                $res = $transaction->where('members.idmember', '=', $query)
                    ->whereBetween(DB::raw('LEFT(transactions.datetrc,10)'), [$dtfrom, $dtto])
                    ->where('transactions.trcstatus', '=', 'CONFIRM')
                    ->get();
            }
            if ($branch != '') {
                $res = $transaction->where('members.idmember', '=', $query)
                    ->where('transactions.idbranch', '=', $branch)
                    ->where('transactions.trcstatus', '=', 'CONFIRM')
                    ->get();
            }
            if ($type != '') {
                $res = $transaction->where('members.idmember', '=', $query)
                    ->where('transactions.trctype', '=', $type)
                    ->where('transactions.trcstatus', '=', 'CONFIRM')
                    ->get();
            }
            $res = $transaction->orderByDesc('transactions.datetrc')->get();
        } else {
            $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')
                ->join('accounts', 'accounts.idacc', '=', 'transactions.idacc')
                ->join('banks', 'banks.idbank', '=', 'accounts.idbank')
                ->select('transactions.*', 'members.username AS mbruser', 'accounts.accname', 'banks.bankcode', 'products.productname', 'branches.branchname', 'users.username');

            if ($query != '') {
                $res = $transaction->where('transactions.trcstatus', '=', 'CONFIRM')
                    ->where('transactions.trctype', '!=', 'BONUS')
                    ->where(function ($where) use ($query) {
                        $where->orWhere('transactions.idtrc', 'LIKE', '%' . $query . '%')
                            ->orWhere('branches.branchname', 'LIKE', '%' . $query . '%')
                            ->orWhere('members.username', '=', $query)
                            ->orWhere('members.mbraccname', 'LIKE', '%' . $query . '%')
                            ->orWhere('accounts.accname', 'LIKE', '%' . $query . '%')
                            ->orWhere('users.username', 'LIKE', '%' . $query . '%');
                    })
                    ->get();
            }
            if ($dtfrom != '' && $dtto != '') {
                $res = $transaction->whereBetween(DB::raw('LEFT(transactions.datetrc,10)'), [$dtfrom, $dtto])
                    ->where('transactions.trcstatus', '=', 'CONFIRM')
                    ->where('transactions.trctype', '!=', 'BONUS')
                    ->get();
            }
            if ($branch != '') {
                $res = $transaction->where('transactions.idbranch', '=', $branch)
                    ->where('transactions.trcstatus', '=', 'CONFIRM')
                    ->where('transactions.trctype', '!=', 'BONUS')
                    ->get();
            }
            if ($type != '') {
                $res = $transaction->where('transactions.trctype', '=', $type)
                    ->where('transactions.trcstatus', '=', 'CONFIRM')
                    ->where('transactions.trctype', '!=', 'BONUS')
                    ->get();
            }
            $res = $transaction->orderByDesc('transactions.datetrc')->get();
        }

        $i = 0;
        $array = array();
        foreach ($res as $data) {
            if ($data->dttype == 'DB') {
                $debet = $data->amount;
                $credit = 0;
            } else if ($data->dttype == 'CR') {
                $debet = 0;
                $credit = $data->amount;
            } else {
                $debet = 0;
                $credit = 0;
            }

            $i++;
            $array[] = array(
                'no' => $i,
                'idtrc' => $data->idtrc,
                'branch' => $data->branchname,
                'datetrc' => $data->datetrc,
                'member' => strtoupper($data->mbruser),
                'product' => $data->productname,
                'account' => '(' . $data->bankcode . ') ' . $data->accname,
                'trctype' => $data->trctype,
                'debet' => number_format($debet),
                'credit' => number_format($credit),
                'fee' => number_format($data->fee),
                'trcstatus' => $data->trcstatus,
                'dateconfirm' => $data->dateconfirm,
                'user' => strtoupper($data->username),
                'created_at' => $data->created_at,
                'idtrc' => $data->idtrc,
                'dttype' => $data->dttype
            );
        }
        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)
    {
        $product = Product::all();
        $requirment = DB::table('accounts')
            // ->join('transactions', 'transactions.idacc', '=', 'accounts.idacc')
            ->join('banks', 'banks.idbank', '=', 'accounts.idbank')
            ->join('branches', 'branches.idbranch', '=', 'accounts.idbranch')
            ->select('accounts.*', 'banks.bankcode', 'branches.branchname')
            ->get();
        $requirment = json_decode($requirment, true);
        // $data = Transaction::find($id);
        // return view('pages.history.edit', compact('product', 'data', 'requirment'));
        $item = Transaction::whereNotNull('note')->get();
        $branches = Branch::all();
        $data = Transaction::find($id);
        return view('pages.history.edit', compact('branches', 'data', 'product', 'requirment', 'item'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\LogTransaction  $logTransaction
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $iduser = Auth::user()->iduser;
        if ($request->trctype == "DEPOSIT") {
            $dtconfirm = date('Y-m-d H:i:s');
            Helper::rdcBalance($request->oldacc, str_replace(',', '', $request->oldamount), 0);
            Helper::addCoin($request->oldbranch, str_replace(',', '', $request->oldamount));
            Helper::addBalance($request->idacc, str_replace(',', '', $request->amount));
            Helper::rdcCoin($request->idbranch, str_replace(',', '', $request->amount));
            $affected = Transaction::find($id)
                ->update([
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idacc' => $request->idacc,
                    'amount' => str_replace(',', '', $request->amount),
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                    'updated_at' => $dtconfirm
                ]);
            if ($affected) {
                Helper::Activity('transaction', $id, 'UPDATE DEPOSIT');
                Alert::success('Success!', 'Data Has Been update!');
                return redirect('history-transaction');
            } else {
                Alert::success('Error!', 'Something When Wrong!');
                return redirect('history-transaction');
            }
        } else if ($request->trctype == "WITHDRAWAL") {
            $dtconfirm = date('Y-m-d H:i:s');
            Helper::addBalance($request->oldacc, str_replace(',', '', $request->oldamount));
            Helper::rdcCoin($request->oldbranch, str_replace(',', '', $request->oldamount));
            Helper::rdcBalance($request->idacc, str_replace(',', '', $request->amount), str_replace(',', '', $request->fee));
            Helper::addCoin($request->idbranch, str_replace(',', '', $request->amount));
            $affected = Transaction::find($id)
                ->update([
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idacc' => $request->idacc,
                    'fee' => str_replace(',', '', $request->fee),
                    'amount' => str_replace(',', '', $request->amount),
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                    'updated_at' => $dtconfirm
                ]);
            if ($affected) {
                Helper::Activity('transaction', $id, 'UPDATE WITHDRAWAL');
                Alert::success('Success!', 'Data Has Been update!');
                return redirect('history-transaction');
            } else {
                Alert::success('Error!', 'Something When Wrong!');
                return redirect('history-transaction');
            }
        } else if ($request->trctype == "OTHER") {
            $dtconfirm = date('Y-m-d H:i:s');
            if ($request->dttype == "DB") {
                Helper::rdcBalance($request->oldacc, str_replace(',', '', $request->oldamount), str_replace(',', '', 0));
                Helper::addBalance($request->idacc, str_replace(',', '', $request->amount));
            } else {
                Helper::addBalance($request->oldacc, str_replace(',', '', $request->oldamount));
                Helper::rdcBalance($request->idacc, str_replace(',', '', $request->amount), str_replace(',', '', 0));
            }
            $affected = Transaction::find($id)
                ->update([
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idproduct' => $request->idproduct,
                    'idacc' => $request->idacc,
                    'amount' => str_replace(',', '', $request->amount),
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                    'updated_at' => $dtconfirm
                ]);
            if ($affected) {
                Helper::Activity('transaction', $id, 'UPDATE OTHER');
                Alert::success('Success!', 'Data Has Been update!');
                return redirect('history-transaction');
            } else {
                Alert::success('Error!', 'Something When Wrong!');
                return redirect('history-transaction');
            }
        } else if ($request->trctype == "BONUS") {
            $dtconfirm = date('Y-m-d H:i:s');
            Helper::addCoin($request->oldbranch, str_replace(',', '', $request->oldamount));
            Helper::rdcCoin($request->idbranch, str_replace(',', '', $request->amount));
            $affected = Transaction::find($id)
                ->update([
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'idproduct' => $request->idproduct,
                    'amount' => str_replace(',', '', $request->amount),
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                    'updated_at' => $dtconfirm
                ]);
            if ($affected) {
                Helper::Activity('transaction', $id, 'UPDATE BONUS');
                Alert::success('Success!', 'Data Has Been update!');
                return redirect('history-transaction');
            } else {
                Alert::success('Error!', 'Something When Wrong!');
                return redirect('history-transaction');
            }
        } else if ($request->trctype == "TRANSFER") {
            $dtconfirm = date('Y-m-d H:i:s');
            $row = Transaction::where('note', '=', $request->note)->get();
            if ($row[0]['dttype'] == "CR") {
                $trc1 = $row[0]['idtrc'];
                $trc2 = $row[1]['idtrc'];
                Helper::addBalance($row[0]['idacc'], str_replace(',', '', $row[0]['amount'] + $row[0]['fee']));
                Helper::rdcBalance($row[0]['idacc'], str_replace(',', '', $request->amount), str_replace(',', '', $request->fee));
                Helper::rdcBalance($row[1]['idacc'], str_replace(',', '', $row[1]['amount']), str_replace(',', '', 0));
                Helper::addBalance($row[1]['idacc'], str_replace(',', '', $request->amount));
            }
            $affected1 = Transaction::find($trc1)
                ->update([
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'fee' => str_replace(',', '', $request->fee),
                    'amount' => str_replace(',', '', $request->amount),
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                    'updated_at' => $dtconfirm
                ]);
            $affected2 = Transaction::find($trc2)
                ->update([
                    'idbranch' => $request->idbranch,
                    'datetrc' => $request->datetrc . ' ' . $request->timetrc,
                    'amount' => str_replace(',', '', $request->amount),
                    'remark' => $request->remark,
                    'iduser' => $iduser,
                    'updated_at' => $dtconfirm
                ]);
            if ($affected1 && $affected2) {
                Helper::Activity('transaction', $request->note, 'UPDATE TRANSFER');
                Alert::success('Success!', 'Data Has Been Saved!');
                return redirect('history-transaction');
            } else {
                Alert::warning('Error!', 'Something When Wrong!');
                return redirect('history-transaction');
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\LogTransaction  $logTransaction
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = Transaction::find($id);
        $res = DB::table('transactions_deleted')->insert([
            'idtrc' => $data['idtrc'],
            'idbranch' => $data['idbranch'],
            'datetrc' => $data['datetrc'],
            'idmember' => $data['idmember'],
            'idproduct' => $data['idproduct'],
            'idacc' => $data['idacc'],
            'dttype' => $data['dttype'],
            'trctype' => $data['trctype'],
            'amount' => $data['amount'],
            'coin' => $data['coin'],
            'fee' => $data['fee'],
            'trcstatus' => $data['trcstatus'],
            'dateconfirm' => $data['$dtconfirm'],
            'note' => $data['note'],
            'remark' => $data['remark'],
            'iduser' => $data['iduser'],
            'created_at' => $data['created_at'],
            'updated_at' => $data['updated_at']
        ]);
        if ($data->trctype == 'DEPOSIT') {
            Helper::Activity('transaction', $id, 'DELETE DEPOSIT');
            @Helper::rdcBalance($data->idacc, $data->amount, $data->fee);
            @Helper::addCoin($data->idproduct, $data->amount);
            $data->delete();
        } else if ($data->trctype == 'WITHDRAWAL') {
            Helper::Activity('transaction', $id, 'DELETE WITHDRAWAL');
            @Helper::rdcCoin($data->idproduct, $data->amount);
            @Helper::addBalance($data->idacc, $data->amount);
            $data->delete();
        } else if ($data->trctype == 'BONUS') {
            Helper::Activity('transaction', $id, 'DELETE BONUS');
            @Helper::addCoin($data->idproduct, $data->amount);
            $data->delete();
        } else if ($data->trctype == "TRANSFER") {
            Helper::Activity('transaction', $data->note, 'DELETE TRANSFER');
            $res = Transaction::where('note', $data->note)->get();
            foreach ($res as $result) {
                if ($result->dttype == "CR") {
                    @Helper::addBalance($result->idacc, $result->amount + $result->fee);
                } else if ($result->dttype == "DB") {
                    @Helper::rdcBalance($result->idacc, $result->amount, $result->fee);
                }
            }
            Transaction::where('note', $data->note)->delete();
        } else {
            if ($data->dttype == "CR") {
                Helper::Activity('transaction', $id, 'DELETE OTHER');
                @Helper::addBalance($data->idacc, $data->amount + $data->fee);
                $data->delete();
            } else if ($data->dttype == "DB") {
                Helper::Activity('transaction', $id, 'DELETE OTHER');
                @Helper::rdcBalance($data->idacc, $data->amount, $data->fee);
                $data->delete();
            } else {
                Helper::Activity('transaction', $id, 'DELETE OTHER');
                $data->delete();
            }
        }
    }
}
