<?php

namespace App\Http\Controllers\Pages;

use Excel;
use App\Imports\MembersImport;
use App\Exports\MembersExport;

use App\Helpers\Helper;
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 App\Models\Ticket;
use App\Models\Spin;
use App\Models\Member;
use App\Models\Reward;
use Response;

class TicketController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $page = 'tickets';
        $page_title = 'Ticket';
        $page_description = 'This is Ticket test page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Ticket'],
            ['page' => 'users', 'title' => 'Data Ticket']
        ];
        $ticket = Ticket::all();
        $members = Member::all();
        return view('pages.ticket.index', compact('ticket', 'page_title', 'page_description', 'page_breadcrumbs', 'page', 'members'));
    }

    public function historys()
    {
        $page = 'historys';
        $page_title = 'History';
        $page_description = 'This is History test page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'History'],
            ['page' => 'users', 'title' => 'Data History']
        ];
        $history = Spin::join('rewards', 'rewards.idreward', '=', 'spins.idreward')
        ->join('tickets', 'tickets.idticket', '=', 'spins.idtiket')
        ->join('members', 'members.idmember', '=', 'tickets.idmember')
        ->get();
        return view('pages.history.index', compact('page_title', 'page_description', 'page_breadcrumbs', 'page', 'history'));
    }
    public function historyShow(Request $request)
    {
        $res = '';
        $query = $request->qr;
        $spin = DB::table('spins')
            ->join('rewards', 'rewards.idreward', '=', 'spins.idreward')
            ->join('tickets', 'tickets.idticket', '=', 'spins.idtiket')
            ->join('members', 'members.idmember', '=', 'tickets.idmember')
            ->select('tickets.idticket', 'members.username', 'rewards.name', 'spins.idspin', 'tickets.number_ticket', 'tickets.spin_date', 'tickets.status', 'tickets.created_at', 'tickets.updated_at');
        if ($query != "null") {
            $res = $spin->where(function ($sql) use ($query) {
                $sql->where('members.username', 'LIKE', '%' . $query . '%');
            })->get();
        } else {
            $res = $spin->orderByDesc('spins.idspin')->get();
        }
        $i = 0;
        $array = array();
        foreach ($res as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'idticket' => $data->idticket,
                'idspin' => $data->idspin,
                'username' => $data->username,
                'name' => $data->name,
                'number_ticket' => $data->number_ticket,
                'spin_date' => $data->spin_date,
                'status' => $data->status,
                'created_at' => $data->created_at,
                'updated_at' => $data->updated_at,
            );
        }
        return Datatables::of($array)->make(true);
    }
    
    

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $ticket = Ticket::all();
        $page = $request->cp;
        return view('pages.ticket.create', compact('ticket', 'page'));
    }

    /**
     * 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(), [
            'idmember' => 'required',
        ]);
        if ($validator->fails()) {
            Alert::warning('Oops!', 'Something When Wrong!');
            if ($request->page == 'transaction') {
                return redirect($request->page)->withErrors($validator);
            } else {
                return redirect('tickets')->withErrors($validator);
            }
        } else {
            $id = IdGenerator::generate(['table' => 'tickets', 'field' => 'idticket', 'length' => 13, 'prefix' => 'TCT' . date('ym')]);
            $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $number_ticket = IdGenerator::generate(['table' => 'tickets', 'field' => 'number_ticket', 'length' => 7, 'prefix' => 'T' . substr(str_shuffle($permitted_chars), 0, 5)]);
            Ticket::create([
                'idticket' => $id,
                'idmember' => $request->idmember,
                'number_ticket' => $number_ticket,
                'status' => 'active',
            ]);
            Helper::Activity('tickets', $id, 'CREATE');
            Alert::success('Success!', 'Data Has Been Saved!');
            if ($request->page == 'transaction') {
                return redirect($request->page);
            } else {
                return redirect('tickets');
            }
        }
    }

    public function ticketImport(Request $request)
    {
        Excel::import(new MembersImport, request()->file('excel_file'));

        return redirect('tickets');
        
    }

    public function ticketExport(Request $request)
    {
        return Excel::download(new MembersExport, 'ticket.xlsx'); 
    }    

    public function ticketExample(Request $request)
    {
        $pathToFile = public_path(). "/testimport.xlsx";
        $fileName = "testimport.xlsx";
        $headers = [
            'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ];
        return Response::download($pathToFile, $fileName, $headers);
    }  

    

    
    

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        $res = '';
        $query = $request->qr;
        $ticket = DB::table('tickets')
            ->join('members', 'tickets.idmember', '=', 'members.idmember')
            ->select('tickets.idticket', 'members.username', 'tickets.number_ticket', 'tickets.spin_date', 'tickets.fixed_reward', 'tickets.status', 'tickets.created_at', 'tickets.updated_at');
        if ($query == 'null') {
            $res = $ticket->orderByDesc('tickets.idticket')->get();
        } else {
            if ($query != null) {
                $res = $ticket->where(function ($sql) use ($query) {
                    $sql->where('members.username', 'LIKE', '%' . $query . '%');
                })->get();
            }
        }
        $i = 0;
        $array = array();
        $fixed_reward = "";
        foreach ($res as $data) {
            $i++;
            $fixed_reward = Reward::where('public_number','=', $data->fixed_reward)->first();
            $fixed_name = "";
            $fixed_reward_id = "";
            if($fixed_reward){
                $fixed_name = $fixed_reward['name'];
                $fixed_reward_id = $fixed_reward['public_number'];
            }
            $array[] = array(
                'no' => $i,
                'idticket' => $data->idticket,
                'username' => $data->username,
                'number_ticket' => $data->number_ticket,
                'spin_date' => $data->spin_date,
                'fixed_reward' => $fixed_name,
                'fixed_reward_id' => $fixed_reward_id,
                'status' => $data->status,
                'created_at' => $data->created_at,
                'updated_at' => $data->updated_at,
            );
        }
        return Datatables::of($array)->make(true);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $page_title = 'Edit Ticket';
        $page_description = 'This is Edit Ticket page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Ticket'],
            ['page' => 'tickets', 'title' => 'Data Ticket'],
            ['page' => 'tickets/' . $id . '/edit', 'title' => 'Edit Ticket']
        ];
        $data = Ticket::join('members', 'tickets.idmember', '=', 'members.idmember')->find($id);
        $allRewards = Reward::where('public_number', '!=', '')->orderBy('public_number', 'asc')->get();
        $fixed_reward = Reward::where('public_number','=', $data->fixed_reward)->first();
        return view('pages.ticket.edit', compact('data', 'page_title', 'page_description', 'page_breadcrumbs', 'allRewards', 'fixed_reward'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        Ticket::find($id)
            ->update([
                'name' => trim($request->name),
                'persentase' => trim($request->percentage),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        Helper::Activity('tickets', $id, 'UPDATE');
        Alert::success('Success!', 'Data has been update!');
        return redirect('tickets');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        DB::table('spins')->where('idtiket', '=', $id)->delete();

        // $spin_history = DB::table('spins')->where('idtiket', '=', $id)->get();

        // foreach ($spin_history as $spin) {
        //     Spin::find($spin['idspin'])->delete();
        // }

        Helper::Activity('tickets', $id, 'DELETE');

        Ticket::find($id)->delete();
    }
}
