<?php

namespace App\Http\Controllers\Pages;

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

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

class PendingController 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 = 'Pending Transactions';
        $page_description = 'This is Pending Transaction';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Transactions'],
            ['page' => 'users', 'title' => 'Pending Transactions']
        ];
        $branches = Branch::all();
        return view('pages.pending.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  int  $id
     * @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;

        $transaction = DB::table('transactions')
            ->join('branches', 'branches.idbranch', '=', 'transactions.idbranch')
            ->join('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', 'accounts.accno', 'banks.bankcode', 'products.productname', 'branches.branchname', 'users.username')
            ->orderByDesc('transactions.datetrc');

        if ($query != '') {
            $res = $transaction->where('transactions.trcstatus', '=', 'PENDING')
                ->where(function ($where) use ($query) {
                    $where->orWhere('branches.branchname', 'LIKE', '%' . $query . '%')
                        ->orWhere('members.idmember', '=', $query)
                        ->orWhere('members.mbraccname', 'LIKE', '%' . $query . '%')
                        ->orWhere('products.productname', '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', '=', 'PENDING')
                ->get();
        }
        if ($branch != '') {
            $res = $transaction->where('transactions.idbranch', '=', $branch)
                ->where('transactions.trcstatus', '=', 'PENDING')
                ->get();
        }
        if ($type != '') {
            $res = $transaction->where('transactions.trctype', '=', $type)
                ->where('transactions.trcstatus', '=', 'PENDING')
                ->get();
        }
        $i = 0;
        $array = array();
        foreach ($res as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'branch' => $data->branchname,
                'datetrc' => $data->datetrc,
                'member' => strtoupper($data->mbruser),
                'product' => $data->productname,
                'account' => '(' . $data->bankcode . ') ' . $data->accname . ' - ' . $data->accno,
                'trctype' => $data->trctype,
                'amount' => number_format($data->amount),
                'trcstatus' => $data->trcstatus,
                'dateconfirm' => $data->dateconfirm,
                'user' => strtoupper($data->username),
                'created_at' => $data->created_at,
                'idtrc' => $data->idtrc
            );
        }
        return Datatables::of($array)->make(true);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $branches = Branch::all();
        $product = Product::all();
        $requirment = DB::table('accounts')
            ->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.pending.edit', compact('branches', 'product', 'data', 'requirment'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $iduser = Auth::user()->iduser;
        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,
            ]);
        Alert::success('Success!', 'Data has been update!');
        return back()->withStatus('pending-transaction');
    }

    public function confirm(Request $request, $id)
    {
        $iduser = Auth::user()->iduser;
        $data = Transaction::find($id);
        // return $data->trctype;
        if ($data->trctype == 'DEPOSIT') {
            @Helper::rdcCoin($data->idproduct, $data->amount);
            @Helper::addBalance($data->idacc, $data->amount);
            $data->update([
                'trcstatus' => 'CONFIRM',
                'dateconfirm' => date('Y-m-d H:i:s'),
                'iduser' => $iduser
            ]);
        } else if ($data->trctype == 'WITHDRAWAL') {
            @Helper::addCoin($data->idproduct, $data->amount);
            @Helper::rdcBalance($data->idacc, $data->amount, $data->fee);
            $data->update([
                'trcstatus' => 'CONFIRM',
                'dateconfirm' => date('Y-m-d H:i:s'),
                'iduser' => $iduser
            ]);
        } else if ($data->trctype == 'BONUS') {
            @Helper::rdcCoin($data->idproduct, $data->amount);
            $data->update([
                'trcstatus' => 'CONFIRM',
                'dateconfirm' => date('Y-m-d H:i:s'),
                'iduser' => $iduser
            ]);
        } else {
            if ($data->dttype = 'DB') {
                @Helper::addBalance($data->idacc, $data->amount);
                $data->update([
                    'trcstatus' => 'CONFIRM',
                    'dateconfirm' => date('Y-m-d H:i:s'),
                    'iduser' => $iduser
                ]);
            } else if ($data->dttype = 'CR') {
                @Helper::rdcBalance($data->idacc, $data->amount, $data->fee);
                $data->update([
                    'trcstatus' => 'CONFIRM',
                    'dateconfirm' => date('Y-m-d H:i:s'),
                    'iduser' => $iduser
                ]);
            } else {
                $data->update([
                    'trcstatus' => 'CONFIRM',
                    'dateconfirm' => date('Y-m-d H:i:s'),
                    'iduser' => $iduser
                ]);
            }
        }
        // Alert::success('Success!', 'Data has been update!');
        // return redirect('pending-transaction');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = Transaction::find($id);
        $save = DB::table('transactions_deleted')->insert([
            'idtrc' => $data['idtrc'],
            'idbranch' => $data['idbranch'],
            'datetrc' => $data['datetrc'],
            'idmember' => $data['idmember'],
            'idacc' => $data['idacc'],
            'dttype' => $data['dttype'],
            'trctype' => $data['trctype'],
            'amount' => $data['amount'],
            'trcstatus' => $data['trcstatus'],
            'dateconfirm' => $data['$dtconfirm'],
            'remark' => $data['remark'],
            'iduser' => $data['iduser'],
            'created_at' => $data['created_at'],
            'updated_at' => $data['updated_at']
        ]);
        if ($save) {
            $data->delete();
            Alert::success('Success!', 'Data has been update!');
        } else {
            Alert::danger('Oops!', 'Something when wrong!');
        }
    }
}
