<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Voucher;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response as HttpFoundationResponse;

class VoucherController extends Controller
{
    public function index(Request $request)
    {
        $data = null;
        $status = '';
        $req_status = 0;
        $message = '';

        try {
            $memberCode = $request->get('memberCode');
            $voucherType = $request->get('voucherType');
            $voucherCode = $request->get('voucherCode');
            $member = Customer::where('phone', $memberCode)->firstOrFail();
            $voucher = Voucher::select(
                DB::raw('"PAYMENT" as voucherType'),
                'voucher_code as voucherCode',
                'item_name as voucherDescription',
                'price_item as amount',
                'price_item as minimumSpending',
                // 'item_code as itemCode',
                // 'item_code as promotionCode',
                // 'item_name as itemName',
                // DB::raw('0 as price'),
                // DB::raw('100 as discount'),
                // DB::raw('0 as minimumSpending'),
                // DB::raw('"3000-12-30 23:59:59" as expiredAt'),
            );
            if ($memberCode && !$voucherCode) {
                $outlet = DB::table('branch')->where('code', $request->outletCode)->first();
                // $voucher = $voucher->whereRaw('price_item <=' . $member->poin . ' and (id_branch = "' . $outlet->id . '" or id_branch = "0" )');
                $voucher = $voucher->whereRaw('id_customer ="' . $member->id . '" and (id_branch = "' . $outlet->id . '" or id_branch = "0" )');
            }
            $cek = false;
            if ($voucherCode) {
                // $data = $voucher->where('voucher_code',$voucherCode)->first();
                $data = $voucher->whereRaw('id_customer ="' . $member->id . '" and voucher_code = "'.$voucherCode.'"')->first();
                if ($data != null) {
                    $cek = true;
                }
            } else {
                $data = $voucher->get();
                if (!$data->isEmpty()) {
                    $cek = true;
                }
            }
                $req_status = HttpFoundationResponse::HTTP_OK;
                $status = true;
                $message = 'Success';

            if ($cek == true) {
                $req_status = HttpFoundationResponse::HTTP_OK;
                $status = true;
                $message = 'Success';
            } else {
                $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
                $status = false;
                $message = 'Outlet or Brand not found';
            }
        } catch (Exception $e) {
            $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
            $status = false;
            $message = 'Outlet or Brand not found';
        } catch (QueryException $e) {
            $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
            $status = false;
            $message = 'Outlet or Brand not found';
        } finally {
            $response = [
                'message' => $message,
                'status' => $status,
                'statusCode' => $req_status,
            ];
            if ($req_status == HttpFoundationResponse::HTTP_OK) {
                if ($voucherCode) {
                    $response['data'] = $data;
                } else {
                    $response['data']['vouchers']['item'] = [];
                    $response['data']['vouchers']['amount'] = !$voucherType || ($voucherType && $voucherType =='PAYMENT') ?  $data : [];
                    $response['data']['benefits']['item'] = [];
                    $response['data']['benefits']['amount'] = [];
                }
            }
            return response()->json($response, $req_status);
        }
    }

    public function burn(Request $request)
    {
        $data = null;
        $status = '';
        $req_status = 0;
        $message = '';

        $status = '';
        $req_status = 0;
        $message = '';

        DB::beginTransaction();
        try {
            $req = $request->all();
            $fields = Validator::make($req, [
                'memberCode' => ['required'],
                'voucherCode' => ['required'],
                'outletCode' => ['required'],
                'minimumSpending' => ['required'],
                'subtotal' => ['required', 'numeric'],
            ], [
                'required' => ':attribute harus diisi.',
            ], [
                'memberCode' => 'Member Code',
                'voucherCode' => 'Voucher Code',
                'outletCode' => 'Outlet Code',
                'minimumSpending' => 'Minimum Spending',
                'subtotal' => 'Subtotal',
            ]);

            if ($fields->fails()) {
                //Send failed response if request is not valid
                $req_status = HttpFoundationResponse::HTTP_UNPROCESSABLE_ENTITY;
                $status = 'failed';
                $message = $fields->errors();
            } else {
                $voucher = Voucher::where('voucher_code', $request->voucherCode)->first();
                if ($voucher != null) {
                    $customer = DB::table('customer')->where('phone', $request->memberCode)->first();

                    $transaction = new Transaction;
                    $transaction->trx_code = "RED-" . time();
                    $transaction->voucher_id = $voucher->id;
                    $transaction->voucher_code = $request->voucherCode;
                    $transaction->voucher_price = $voucher->price_item;
                    $transaction->id_cust = $customer->id;
                    $transaction->poin = $customer->poin - $voucher->price_item;
                    $transaction->amount = $request->subtotal;
                    $transaction->tipe = '1';
                    $transaction->tgl_trx = date('Y-m-d H:i:s');
                    $transaction->id_branch = $voucher->id_branch;
                    $transaction->save();

                    $burn = [
                        'poin' => $customer->poin - $voucher->price_item,
                    ];
                    DB::table('customer')->where('phone', $request->memberCode)->update($burn);
                    Voucher::where('voucher_code',$request->voucherCode)->delete();
                    // $lastCode = Voucher::max('voucher_code');
                    // $lastCode = substr($lastCode,1);
                    // $lastCode = (int) $lastCode + 1;
                    // $code = "V".sprintf("%05s", $lastCode);;
        
                    // $updateVoucher = Voucher::where('voucher_code',$request->voucherCode)->firstOrfail();
                    // $updateVoucher->voucher_code = $code;
                    // $updateVoucher->save();
                    
                    $req_status = HttpFoundationResponse::HTTP_OK;
                    $status = true;
                    $message = 'Burn Voucher success';
                    $data = [
                        "voucherCode" => $request->voucherCode,
                        "status" => true,
                    ];
                } else {
                    $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
                    $status = false;
                    $message = 'Outlet or Brand not found';
                }
            }
        } catch (Exception $e) {
            DB::rollBack();
            $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
            $status = false;
            $message = 'Outlet or Brand not found';
        } catch (QueryException $e) {
            DB::rollBack();
            $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
            $status = false;
            $message = 'Outlet or Brand not found';
        } finally {
            DB::commit();
            $response = [
                'message' => $message,
                'status' => $status,
                'statusCode' => $req_status,
            ];
            if ($req_status == HttpFoundationResponse::HTTP_OK) {
                $response['data'] = $data;
            }
            return response()->json($response, $req_status);
        }
    }
    public function transaction(Request $request)
    {
        $data = null;
        $status = '';
        $req_status = 0;
        $message = '';

        $status = '';
        $req_status = 0;
        $message = '';

        DB::beginTransaction();
        try {
            $refNumber = bin2hex(random_bytes(20));
            $req = $request->all();
            $persentase = DB::table('master')->first();
            $customer = DB::table('customer')->select('customer.*','member_categories.percent')->join('member_categories','customer.category_id','member_categories.id')->where('phone', $request->memberCode)->first();
            $branch = DB::table('branch')->where('code', $request->outletCode)->first();
            $voucher = 0;
            if($request->voucherClaimed){
                foreach($request->voucherClaimed as $key => $value){
                    $voucher+=$value['discount'];
                }
            }
            $tax = $request->taxService ? $request->taxService : 0;
            $total = $request->grandTotal - $voucher - $tax;            
            $transaction = new Transaction;
            $transaction->trx_code = $request->esbOrderID && $request->esbOrderID != null ? $request->esbOrderID : "POS-" . time();
            $transaction->voucher_id = null;
            $transaction->voucher_code = null;
            $transaction->id_cust = $customer->id;
            $transaction->poin_earned = $customer->percent / 100 * $total;
            $transaction->poin = $customer->poin + $transaction->poin_earned;
            $transaction->amount = $request->grandTotal - $tax;
            $transaction->tipe = '0';
            $transaction->tgl_trx = $request->transDate;
            $transaction->id_branch = $branch->id;
            $transaction->ref_number = $refNumber;
            $transaction->save();

            $updatePoint = [
                'poin' => $transaction->poin,
            ];
            DB::table('customer')->where('phone', $request->memberCode)->update($updatePoint);


            $req_status = HttpFoundationResponse::HTTP_OK;
            $data = [
                "status" => true,
                "statusCode" => 200,
                "message" => 'Received. Please check the final transaction status by using below Reference Number',
                "referenceNumber" => $refNumber,
            ];
        } catch (Exception $e) {
            DB::rollBack();
            $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
        } catch (QueryException $e) {
            DB::rollBack();
            $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
        } finally {
            DB::commit();
            $response = [
                'statusCode' => $req_status,
                'message' => ['outletCode should not be empty'],
                'error' => 'Bad Request'
            ];

            if ($req_status == HttpFoundationResponse::HTTP_OK) {
                $response = $data;
            }
            return response()->json($response, $req_status);
        }
    }
}
