<?php

namespace App\Http\Controllers\Pages;

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

use App\Models\{Coin, Branch};

class CoinController 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 = 'Coin';
        $page_description = 'This is Coin Page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Coin'],
            ['page' => 'coins', 'title' => 'Coin Product']
        ];
        return view('pages.coin.index', compact('page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $page_title = 'Add Coin';
        $page_description = 'This is Add Coin Page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Coin'],
            ['page' => 'Coin', 'title' => 'Add Coin Branch']
        ];
        $branch = Branch::all();
        return view('pages.coin.create', compact('branch', '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)
    {
        $validator = Validator::make($request->all(), [
            'idbranch' => 'required',
            'datetrc' => 'required',
            'opening' => 'required'
        ]);
        if ($validator->fails()) {
            Alert::warning('Oops!', 'Something When Wrong!');
            return redirect('coins')->withErrors($validator);
        } else {
            $id = IdGenerator::generate(['table' => 'coins', 'field' => 'idcoin', 'length' => 13, 'prefix' => 'COIN' . date('ym')]);
            $affected = Coin::create([
                'idcoin' => $id,
                'idbranch' => $request->idbranch,
                'dtopening' => $request->datetrc,
                'opening' => str_replace(',', '', $request->opening),
                'running' => str_replace(',', '', $request->opening),
                'closing' => 0,
                'iduser' => Auth::user()->iduser,
            ]);
            if ($affected) {
                Helper::Activity('coins', $id, 'CREATE');
                Alert::success('Success!', 'Data Has Been Saved!');
                return redirect('coins');
            } else {
                Alert::success('Error!', 'Something When Wrong!');
                return redirect('coins');
            }
        }
    }

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

        $result = DB::table('coins')
            ->join('branches', 'branches.idbranch', '=', 'coins.idbranch')
            ->join('users', 'coins.iduser', '=', 'users.iduser')
            ->select('coins.*', 'branches.branchname', 'users.username')
            ->orderByDesc('coins.created_at');

        if ($query != '') {
            $res = $result->orWhere('branches.branchname', 'LIKE', '%' . $query . '%')
                ->get();
        }
        if ($dtfrom != '' && $dtto != '') {
            $res = $result->whereBetween('coins.dtopening', [$dtfrom, $dtto])
                ->get();
        }

        $i = 0;
        $array = array();
        foreach ($res as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'branch' => $data->branchname,
                'dtopening' => $data->dtopening,
                'opening' => number_format($data->opening),
                'running' => number_format(@Helper::runCoin($data->idbranch, $dtfrom, $dtto)),
                'dtclosing' => $data->dtclosing,
                'closing' => number_format($data->closing),
                'created_at' => $data->created_at,
                'user' => strtoupper($data->username),
                'idcoin' => $data->idcoin,
            );
        }
        return Datatables::of($array)->make(true);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Coin  $Coin
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $page_title = 'Edit Coin';
        $page_description = 'This is Edit Coin Page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Coin'],
            ['page' => 'Coin', 'title' => 'Edit Coin Bank']
        ];
        $branch = Branch::all();
        $coin = Coin::find($id);
        return view('pages.coin.edit', compact('coin', 'branch', 'page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Coin  $Coin
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $affected = Coin::find($id)
            ->update([
                'dtopening' => $request->dtopening,
                'opening' => str_replace(',', '', $request->opening),
                'running' => str_replace(',', '', $request->opening),
                'dtclosing' => $request->dtclosing,
                'closing' => str_replace(',', '', $request->closing),
                'remark' => $request->remark,
                'iduser' => Auth::user()->iduser,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        if ($affected) {
            Helper::Activity('coins', $id, 'UPDATE');
            Alert::success('Success!', 'Data has been update!');
            return redirect('coins');
        }
    }

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