<?php

namespace App\Http\Controllers;

use App\Models\MemberCard;
use App\Models\StikerTrans;
use App\Models\StikerTransDetail;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Js;
use Yajra\DataTables\Facades\DataTables;

class MemberStikerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $vehicleSelect = DB::table('jenis_mobil')->get();
        $departmentSelect = DB::table('stasiunkerja')->get();
        $memberSelect = DB::table('jenis_langganan')->get();
        $jenisStiker = DB::table('tarif_stiker')->get();
        
        return view('member.member', compact([
            'vehicleSelect',
            'departmentSelect',
            'memberSelect',
            'jenisStiker',
        ]));
    }

    public function getMember (Request $request) 
    {
        Log::info(json_encode('nopol : ' .$request->nopol));
        Log::info(json_encode('veh : ' .$request->vehicle));
        Log::info(json_encode('dept : ' .$request->depart));
        Log::info(json_encode('mem : ' .$request->member));
        Log::info(json_encode('trans : ' .$request->notrans));
        Log::info(json_encode('isactive : ' .gettype($request->isactive)));
        if ($request->ajax() ) {

            
            $dataStiker = DB::table('transaksi_stiker as ts')
            ->leftjoin('detail_transaksi_stiker as dts','dts.notrans','=','ts.notrans')
            ->leftJoin('card_member as cm','cm.notrans','=','ts.no_id')
            ->leftJoin('jenis_langganan as jl','jl.id','=','ts.jenis_langganan')
            ->leftJoin('stasiunkerja as sk','sk.kode','=','ts.unit_kerja')
            ->leftJoin('jenis_mobil as jm','jm.id','=','dts.jenis_mobil')
            ->select(DB::raw('
                ts.notrans as notrans , ts.nama , ts.alamat as alamat , ts.telepon as telepon, 
                ts.awal as awal , ts.akhir as akhir, jl.nama as jmember, sk.nama as dept, dts.nopol, 
                jm.nama vehicle, dts.jenis_member, cm.no_card as no_card'))
                ->distinct();
            // ->select(DB::raw('ts.notrans as notrans , ts.nama , ts.alamat as alamat , ts.telepon as telepon , ts.awal as awal , ts.akhir as akhir, sk.nama as unit_kerja, jl.nama as jenis_member, ts.no_id'))
            
            if ($request->nama) {
                $dataStiker = $dataStiker->where('ts.nama', 'like', '%' . $request->nama . '%');
            }

            if ( $request->notrans) {
                $dataStiker = $dataStiker->where('ts.notrans', 'like', '%' . $request->notrans . '%');
            }

            if ($request->nopol) {
                $dataStiker = $dataStiker->where('ts.unit_kerja', 'like', '%' . $request->depart . '%');
            }
            
            if ($request->member) {
                $dataStiker = $dataStiker->where('ts.jenis_langganan', 'like', '%' . $request->member . '%');
            }
            
            if ($request->nopol) {
                $dataStiker = $dataStiker->where('dts.nopol', 'like', '%' . $request->nopol . '%');
            }
             
            if ($request->vehicle) {
                $dataStiker = $dataStiker->where('dts.jenis_mobil', 'like', '%' . $request->vehicle . '%');
            }

            if ($request->nocard) {
                $dataStiker = $dataStiker->where('cm.no_card', 'like', '%' . $request->nocard . '%');
            }

            if ($request->isactive === '1') {
                $dataStiker = $dataStiker->whereRaw('now() between ts.awal and ts.akhir');
            }

            Log::info($dataStiker->toSql());
            
            $dataStiker = $dataStiker->get();

            return response()->json($dataStiker);
        }

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        Log::info('Data yang diperpanjang : ' . json_encode($request->all()));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */

    public function checkField (Request $request)
    {
        Log::info('Data yang diterima : ' . json_encode($request->all()));
        $validate = Validator::make($request->all(),[
            'nopol' => 'required|string|unique:detail_transaksi_stiker,nopol',
            // 'nocard' => 'string|exists:card_member,no_card',
        ]);
        
        $nocard = $request->input('nocard');
        $nocardExists = DB::table('card_member')
        ->where('no_card', $nocard)
        ->exists();

        if ($validate->fails()) {
            return response()->json(['response' => false, 'message' => 'Data sudah ada, coba yang lain']);
        }

        return response()->json(['response' => true, 'message' => 'Data sudah ada']);

    }

    public function store(Request $request)
    {
        Log::info('Data yang diterima : ' . json_encode($request->all()));
        $mountYearNow = Carbon::now()->format('m/Y');

        $dataStiker = $request->input('formData');
        $dataVehicle = $request->input('nopolData');
        $dataCard = $request->input('cardNumber');
        Log::info('Data Stiker : ' . json_encode($dataStiker));
        Log::info('Data Kendaraan : ' . json_encode($dataVehicle));
        Log::info('Data kartu : ' . json_encode($dataCard));
        // $cleanedData = stripslashes(trim($data));
        // Log::debug('Modified : ' . json_encode($cleanedData));
        // $dataStiker = json_decode($cleanedData, false);
        // Log::info('Debuggind data : ' . json_encode($dataStiker));

        // $validate = Validator::make($request->all(),[
        //     'nama' => 'required|string|unique',
        //     // 'nopol' => 'required|string|unique:detail_transaksi_stiker,nopol',
        //     // 'nocard' => 'string|exists:card_member,no_card',
        // ]);

        // if ($validate->fails()) {
        //     return response()->json(['response' => false, 'message' => 'pastikan nama, Nomor Polisi, dan data kartu sudah terisi']);
        // }

        $dateNow = Carbon::now()->format('Y-m-d H:m:s');
        $seqTrans = DB::table('indexnum')->select('value')->where('nama', 'sticker')->first();
        $seqId = DB::table('indexnum')->select('value')->where('nama', 'identitas')->first();

        $notrans = $seqTrans->value . "/STK/" . $mountYearNow;
        $noid = $seqId->value . "/IDT/" . $mountYearNow;
        $user = Auth::user();

        $periode = explode(" - ", $dataStiker['daterange']);
        Log::info('Parcing Periode : ' . json_encode($periode));
        $awal = Carbon::createFromFormat('d-m-Y H:i', $periode[0]);
        $akhir = Carbon::createFromFormat('d-m-Y H:i', $periode[1]);
        Log::info('Awal : ' . $awal . ' Akhir : ' . $akhir);
        // Log::info($user);

        try {
            $dataStiker = [
                'jenis_transaksi' => $dataStiker['jenis_transaksi'], // 0 = transaksi baru , 1 = perpanjangan
                'notrans' => $notrans,
                'no_id' => $noid,
                'nama' => $dataStiker['nama'],
                'alamat' => $dataStiker['address'] ?? '',
                'telepon' => $dataStiker['phone'] ?? '', 
                'unit_kerja' => $dataStiker['depart'], 
                'jenis_stiker' => $dataStiker['member'], 
                'awal' => $awal, 
                'akhir' => $akhir,
                'harga' => $dataStiker['harga'] ?? 0, 
                'keterangan' => $dataStiker['note'] ?? '', 
                'tanggal' => $dateNow, 
                'operator' => $user->nomer,
            ];

            DB::table('transaksi_stiker')->insert($dataStiker);

            if($dataVehicle) {
                foreach ($dataVehicle as $nopol) {
                    $dataVehicle = [
                        'notrans' => $notrans,
                        'nopol' => $nopol['nopol'],
                        'jenis_mobil' => $nopol['vehicle'],
                        'jenis_member' => $nopol['member'],
                        'merk' => $nopol['merk'],
                    ];
                    DB::table('detail_transaksi_stiker')->insert($dataVehicle);
                }
            } else {
                return 0;;
            }
            
            if ($dataCard) {
                foreach ($dataCard as $cardNumber) {
                    $dataCard = [
                        'notrans' => $noid,
                        'no_card' => $cardNumber['nocard'],
                        'no_urut' => $cardNumber['nourut'],
                    ];

                    DB::table('card_member')->insert($dataCard);
                }
            } else {
                return 0;
            }

            DB::table('indexnum')->where('nama', 'sticker' )->update(['value' => DB::raw("lpad(to_number(value,'9999')+1)::text, 4, '0')")]);
            DB::table('indexnum')->where('nama', 'identitas' )->update(['value' => DB::raw("lpad(to_number(value,'9999')+1)::text, 4, '0')")]);
            $response = true;
            $msg = 'Data berhasil di simpan';
        } catch (Exception $e) {
            $response = false;
            $msg = 'Gagal menyimpan data ' . $e->getMessage() . $e->getLine();
        }
        
        return response()->json(['response' => $response, 'pesan' => $msg]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        Log::info('Data yang diterima : ' . json_encode($id));
        $dataStiker = StikerTrans::with('stiker_details.vehicle', 'memberCard')
            ->select('transaksi_stiker.notrans', 'transaksi_stiker.nama', 'transaksi_stiker.alamat', 'transaksi_stiker.telepon', 'transaksi_stiker.awal', 'transaksi_stiker.akhir', 'transaksi_stiker.jenis_langganan', 
                'transaksi_stiker.unit_kerja', 'transaksi_stiker.no_id', 'jl.nama as jmember', 'sk.nama as dept')
            ->leftJoin('jenis_langganan as jl','jl.id','=','transaksi_stiker.jenis_langganan')
            ->leftJoin('stasiunkerja as sk','sk.kode','=','transaksi_stiker.unit_kerja')
            ->where('notrans', 'like', '%' . $id . '%')
            ->first();
        // $dataStiker = DB::table('transaksi_stiker as ts')
        //     ->leftjoin('detail_transaksi_stiker as dts','dts.notrans','=','ts.notrans')
        //     ->leftJoin('jenis_langganan as jl','jl.id','=','ts.jenis_langganan')
        //     ->leftJoin('stasiunkerja as sk','sk.kode','=','ts.unit_kerja')
        //     ->leftJoin('jenis_mobil as jm','jm.id','=','dts.jenis_mobil')
        //     ->leftJoin('card_member as cm','cm.notrans','=','ts.no_id')
        //     ->select(DB::raw('
        //         ts.notrans as notrans , ts.nama , ts.alamat as alamat , ts.telepon as telepon, 
        //         ts.awal as awal , ts.akhir as akhir, jl.nama as jmember, sk.nama as dept, dts.nopol, 
        //         jm.nama vehicle, dts.jenis_member, cm.no_card as no_card')
        //     )->where('ts.notrans', 'like', '%' . $id . '%')
        //     ->get();
        Log::info('Data Stiker : ' . json_encode($dataStiker));

        return response()->json($dataStiker);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
