<?php

namespace App\Http\Controllers\Pages;

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

use App\Imports\BonusesImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\{Transaction, Branch, Bonus};

class BonusController 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 = 'Bonus';
        $page_description = 'This is Data Bonus';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Bonus'],
            ['page' => 'bonus', 'title' => 'Data Bonus']
        ];
        $branches = Branch::all();
        return view('pages.bonus.index', compact('branches', 'page_title', 'page_description', 'page_breadcrumbs'));
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $page_title = 'Bonus';
        $page_description = 'This is Add Bonus';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Bonus'],
            ['page' => 'bonus', 'title' => 'Add Bonus']
        ];
        $branches = Branch::all();
        return view('pages.bonus.create', compact('branches', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    public function import()
    {
        $page_title = 'Bonus';
        $page_description = 'This is Import Bonus';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Bonus'],
            ['page' => 'bonus', 'title' => 'Import Bonus']
        ];
        $branches = Branch::all();
        return view('pages.bonus.import', compact('branches', '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)
    {
        $file = $request->file('customFile');
        Excel::import(new BonusesImport, $file);
        Helper::Activity('bonus', '', 'IMPORT');
        Alert::success('Success!', 'Data has been saved!');
        return back()->withStatus('Success! Data has been saved.');
    }

    /**
     * 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;
        $branch = $request->br;

        $transaction = DB::table('transactions')
            ->join('branches', 'branches.idbranch', '=', 'transactions.idbranch')
            ->join('members', 'members.idmember', '=', 'transactions.idmember')
            ->join('users', 'users.iduser', '=', 'transactions.iduser')
            ->select('transactions.*', 'members.username AS mbruser', 'branches.branchname', 'users.username')
            ->orderByDesc('transactions.datetrc');
        if ($query != '' || $query != null) {
            $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.fullname', 'LIKE', '%' . $query . '%')
                        ->orWhere('members.username', 'LIKE', '%' . $query . '%')
                        ->orWhere('users.username', 'LIKE', '%' . $query . '%');
                })
                ->get();
        }
        if ($branch != '' || $branch != null) {
            $res = $transaction->where('transactions.idbranch', '=', $branch)
                ->where('transactions.trctype', '=', 'BONUS')
                ->where('transactions.trcstatus', '=', 'CONFIRM')
                ->get();
        }
        if ($dtfrom != '' && $dtto != '' || $dtfrom != null && $dtto != null) {
            $res = $transaction->whereBetween(DB::raw('LEFT(transactions.datetrc,10)'), [$dtfrom, $dtto])
                ->where('transactions.trctype', '=', 'BONUS')
                ->where('transactions.trcstatus', '=', 'CONFIRM')
                ->get();
        }

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

    public function draft(Request $request)
    {
        $res = '';
        $query = $request->qr;
        $dtfrom = $request->df;
        $dtto = $request->dt;
        $branch = $request->br;

        $transaction = DB::table('bonuses')
            ->join('branches', 'branches.idbranch', '=', 'bonuses.idbranch')
            ->join('members', 'members.idmember', '=', 'bonuses.idmember')
            ->join('users', 'users.iduser', '=', 'bonuses.iduser')
            ->select('bonuses.*', 'members.username AS mbruser', 'branches.branchname', 'users.username');

        if ($query != '' || $query != null) {
            $res = $transaction->where('bonuses.bnstatus', '=', 'DRAFT')
                ->where(function ($where) use ($query) {
                    $where->orWhere('bonuses.remark', 'LIKE', '%' . $query . '%')
                        ->orWhere('branches.branchname', 'LIKE', '%' . $query . '%')
                        ->orWhere('members.username', 'LIKE', '%' . $query . '%')
                        ->orWhere('users.username', 'LIKE', '%' . $query . '%');
                })
                ->get();
        }
        if ($branch != '' || $branch != null) {
            $res = $transaction->where('bonuses.idbranch', '=', $branch)
                ->where('bonuses.bnstatus', '=', 'DRAFT')
                ->get();
        }
        if ($dtfrom != '' && $dtto != '' || $dtfrom != null && $dtto != null) {
            $res = $transaction->whereBetween(DB::raw('LEFT(bonuses.created_at,10)'), [$dtfrom, $dtto])
                ->whereBetween(DB::raw('LEFT(bonuses.created_at,10)'), [$dtfrom, $dtto])
                ->where('bonuses.bnstatus', '=', 'DRAFT')
                ->get();
        }

        $i = 0;
        $array = array();
        foreach ($res as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'branch' => $data->branchname,
                'member' => strtoupper($data->mbruser),
                'amount' => number_format($data->amount),
                'prdfrom' => $data->dtfrom,
                'prdto' => $data->dtto,
                'remark' => $data->remark,
                'bnstatus' => $data->bnstatus,
                'user' => strtoupper($data->username),
                'created_at' => $data->created_at,
                'idbonus' => $data->idbonus
            );
        }
        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();
        $data = Transaction::find($id);
        return view('pages.bonus.edit', compact('branches', 'data'));
    }

    /**
     * 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;
        $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,
            ]);
        if ($affected) {
            Helper::Activity('bonus', $id, 'UPDATE');
            Alert::success('Success!', 'Data Has Been update!');
            return redirect('bonus');
        } else {
            Alert::success('Error!', 'Something When Wrong!');
            return redirect('bonus');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @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'],
            'idacc' => $data['idacc'],
            'dttype' => $data['dttype'],
            'trctype' => $data['trctype'],
            'amount' => $data['amount'],
            '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 == 'BONUS') {
            Helper::Activity('bonus', $data['idtrc'], 'DELETE');
            Helper::addCoin($data->idproduct, $data->amount);
            $data->delete();
        }
    }

    public function confirm(Request $request, $id)
    {
        $dtconfirm = date('Y-m-d H:i:s');
        $idtrc = IdGenerator::generate(['table' => 'transactions', 'field' => 'idtrc', 'length' => 13, 'prefix' => 'TRC' . date('m')]);
        $bonus = Bonus::where('idbonus', $id);
        $data = $bonus->get();
        Helper::rdcCoin($data[0]->idbranch, $data[0]->amount);
        $affected = Transaction::create([
            'idtrc' => $idtrc,
            'idbranch' => $data[0]->idbranch,
            'datetrc' => $dtconfirm,
            'idmember' => $data[0]->idmember,
            'dttype' => '-',
            'trctype' => 'BONUS',
            'amount' => 0,
            'coin' => $data[0]->amount,
            'trcstatus' => 'CONFIRM',
            'dateconfirm' => $dtconfirm,
            'remark' => $data[0]->remark,
            'iduser' => Auth::user()->iduser,
        ]);
        if ($affected) {
            Helper::Activity('bonus', $idtrc, 'CONFIRM');
            $bonus->update([
                'bnstatus' => 'CONFIRM',
                'confirmed_at' => date('Y-m-d H:i:s')
            ]);
        }
        return back()->withStatus('Success!');
    }

    public function confirmall(Request $request)
    {
        $all = count($request->id);
        $dtconfirm = date('Y-m-d H:i:s');
        for ($i = 0; $i < $all; $i++) {
            $id = $request->id;
            $idtrc = IdGenerator::generate(['table' => 'transactions', 'field' => 'idtrc', 'length' => 13, 'prefix' => 'TRC' . date('m')]);
            $bonus = Bonus::whereIn('idbonus', $id);
            $data = $bonus->get();
            Helper::rdcCoin($data[$i]->idbranch, $data[$i]->amount);
            $affected = Transaction::create([
                'idtrc' => $idtrc,
                'idbranch' => $data[$i]->idbranch,
                'datetrc' => $dtconfirm,
                'idmember' => $data[$i]->idmember,
                'dttype' => '-',
                'trctype' => 'BONUS',
                'amount' => 0,
                'coin' => $data[$i]->amount,
                'trcstatus' => 'CONFIRM',
                'dateconfirm' => $dtconfirm,
                'remark' => $data[$i]->remark,
                'iduser' => Auth::user()->iduser,
            ]);
            if ($affected) {
                Helper::Activity('bonus', '', 'CONFIRM ALL');
                $bonus->update([
                    'bnstatus' => 'CONFIRM',
                    'confirmed_at' => date('Y-m-d H:i:s')
                ]);
            }
        }
        // return back()->withStatus('Success!');
    }

    public function delete($id)
    {
        Helper::Activity('bonus', $id, 'DELETE');
        Bonus::find($id)->delete();
    }
}
