<?php

namespace App\Http\Controllers;

use App\PurchaseOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Classes\Service\Base64Uploader;
use App\Booking;
use App\Rate;
use App\UserBankSlip;
use App\User;
use App\Invoice;
use App\SettingCredit;
use App\SettingTaxRate;
use App\SettingBillingCharge;
use App\Notification;
use Auth;
use Validator;
use Carbon\Carbon;
use DateTime;

class BookingController extends Controller
{

    public function index(){
        $bookings = Booking::UserBooking(Auth::user()->id)->InCompleteOrders()
            ->where('is_cancel', 0)
            ->orderby('updated_at','desc')
            ->paginate(10);
                                

        // reformat to fit frontend structure 
        foreach ($bookings as $booking) {
            // set timeout 
            $date1 = new DateTime($booking->created_at);
            $date2 = new DateTime();
            $time_in_seconds = SettingCredit::orderby('updated_at','desc')->first()->time_limit;
            $difference_in_seconds = ($date1->format('U') + $time_in_seconds) - ($date2->format('U'));
            $booking->timeout = $difference_in_seconds; 

            // TODO : you can make it better
            if($difference_in_seconds < 0 ){
                $booking->timeout = 0;
            }
            
            $booking->track_status = "(". $booking->status ."/7)";

            $booking->service_charge = 0;
            if ($booking->term === "x2_cash" || $booking->term === "x2_cheque" || $booking->term === "x2_ba"){
                $booking->track_status = "(". $booking->status ."/5)";
                if ($booking->amount < 10000){
                    $booking->service_charge = 20;
                }
            }

            // TODO : transfer_amount change name to bia
            $booking->transfer_amount = $booking->bia;

            switch ($booking->status) {
                case 1:
                    $status_desc = "Order in progress"; 
                    break;
                case 2:
                    $status_desc = "Waiting for payment";  
                    break;    
                case 3:
                    $status_desc = "Waiting verification";    
                    break;  
                case 4:
                    $status_desc = "Processing transfer"; 
                    break;
                case 5:
                    $status_desc = "Transfer Complete, please upload your PO"; 
                    break;
                case 6:
                    $status_desc = "Processing invoice";
                    break;
                case 7:
                    $status_desc = "Order Completed"; 
                    break;
                default:
                    $status_desc = "";
            }
            $booking->status_desc = $status_desc;
            $booking->marking = $booking->user->marking;
        }
       
        return $bookings;
    }

    public function userComplete(){
        $bookings = Booking::UserBooking(Auth::user()->id)->CompleteOrders()->orderby('updated_at','desc')->paginate(200);

        // reformat to fit frontend structure 
        foreach ($bookings as $booking) {
            // set timeout 
            $date1 = new DateTime($booking->created_at);
            $date2 = new DateTime();
            $time_in_seconds = SettingCredit::orderby('updated_at','desc')->first()->time_limit;
            $difference_in_seconds = ($date1->format('U') + $time_in_seconds) - ($date2->format('U'));
            $booking->timeout = $difference_in_seconds; 

            // TODO : you can make it better
            if($difference_in_seconds < 0 ){
                $booking->timeout = 0;
            }
            
            $booking->track_status = "(". $booking->status ."/7)";

            // all x2 until step 5 only
            $booking->service_charge = 0;
            if ($booking->term === "x2_cash" || $booking->term === "x2_cheque" || $booking->term === "x2_ba"){
                $booking->track_status = "(". $booking->status ."/5)";
                if ($booking->amount < 10000) {
                    $booking->service_charge = 20;
                }
            }

            // TODO : transfer_amount change name to bia
            $booking->transfer_amount = $booking->bia;

            $booking->status_desc = "Order Completed";
            $booking->marking = $booking->user->marking;
        }
       
        return $bookings;
    }
	
	public function adminIndex(?string $userId = null){
		$bookings = Booking::UserBooking($userId)->InCompleteOrders()->orderby('updated_at', "desc")->paginate(200);

        // reformat to fit frontend structure
        foreach ($bookings as $booking) {
            // set timeout
            $date1 = new DateTime($booking->created_at);
            $date2 = new DateTime();
            $time_in_seconds = SettingCredit::orderby('updated_at','desc')->first()->time_limit;
            $difference_in_seconds = ($date1->format('U') + $time_in_seconds) - ($date2->format('U'));
            $booking->timeout = $difference_in_seconds;

            // TODO : you can make it better
            if($difference_in_seconds < 0 ){
                $booking->timeout = 0;
            }

            $booking->service_charge = 0;
            if ($booking->term === "x2_cash" || $booking->term === "x2_cheque" || $booking->term === "x2_ba"){
                $booking->track_status = "(". $booking->admin_status ."/6)";
                if ($booking->amount < 10000) {
                    $booking->service_charge = 20;
                }
            }
            else{
                $booking->track_status = "(". $booking->admin_status ."/7)";
            }

            // TODO : transfer_amount change name to bia
            $booking->transfer_amount = $booking->bia;

            switch ($booking->admin_status) {
                case 1:
                    $status_desc = "Waiting customer upload bank slip";
                    break;
                case 2:
                    $status_desc = "Verify user bank slip";
                    break;
                case 3:
                    $status_desc = "Generate supplier booking report";
                    break;
                case 4:
                    $status_desc = "Supplier booking report. Please confirm with your booking.";
                    break;
                case 5:
                    $status_desc = "Please, upload China Bankslip";
                    break;
                case 6:
                    $status_desc = "Waiting customer to upload purchase order";
                    if ($booking->term == "x2_cash" || $booking->term == "x2_cheque" || $booking->term == "x2_ba"){
                        $status_desc = "Order Completed";
                    }
                    break;
                case 7:
                    $status_desc = "Customer has uploaded purchase order, please upload invoice";
                    break;
                case 8:
                    $status_desc = "Booking Completed";
                    break;
                default:
                    $status_desc = "";
            }
            $booking->marking = $booking->user->marking;
            $booking->status_desc = $status_desc;
        }
        return $bookings;
	}

    public function adminBookComplete(?string $userId = null){
		$user = Auth::user(); 
		$bookings = Booking::UserBooking($userId)->CompleteOrders()->orderby('updated_at', "desc")->paginate(200);
			// reformat to fit frontend structure 
			foreach ($bookings as $booking) {
				// set timeout 
				$date1 = new DateTime($booking->created_at);
				$date2 = new DateTime();
				$time_in_seconds = SettingCredit::orderby('updated_at','desc')->first()->time_limit;
				$difference_in_seconds = ($date1->format('U') + $time_in_seconds) - ($date2->format('U'));
				$booking->timeout = $difference_in_seconds;  

				// TODO : you can make it better
				if($difference_in_seconds < 0 ){
					$booking->timeout = 0;
				}

				// TODO : transfer_amount change name to bia 
				$booking->transfer_amount = $booking->bia; 
		
                $booking->service_charge = 0;
                if ($booking->term === "x2_cash" || $booking->term === "x2_cheque" || $booking->term === "x2_ba"){
                    $booking->track_status = "(". $booking->admin_status ."/6)";
                    if ($booking->amount < 10000) {
                        $booking->service_charge = 20;
                    }
                }
                else{
				    $booking->track_status = "(". $booking->admin_status ."/7)";
                }

                // TODO : transfer_amount change name to bia
                $booking->transfer_amount = $booking->bia;

                $booking->marking = $booking->user->marking;
				$booking->status_desc = "Booking Completed";
			}
			return $bookings;
	}
    public function show($id)
    {   
        $booking = Booking::where('user_id',Auth::user()->id)->where('id', $id)->first();


		if($booking){

            $date1 = new DateTime($booking->created_at);
            
            $user_bankslip = $booking->userBankSlip()->first();
            $china_bankslip = $booking->chinaBankSlip()->get();

            $po = $booking->purchaseOrder()->get();
            $invoice = $booking->invoice()->get();

            if ($user_bankslip){
                $booking->user_bankslip_path = Storage::url($user_bankslip->bankslip_path);
                $booking->reject_reason = $user_bankslip->reject_reason;
                $date1 = new DateTime($user_bankslip->updated_at);
            }

            if($china_bankslip){
                for($index = 0;$index < $booking->chinaBankSlip()->count();$index++){
                    $china_bankslip[$index] = Storage::url($china_bankslip[$index]->china_bank_slip_path);
                }
                $booking->china_bankslip_path = $china_bankslip;

                //temporary block
                if($booking->created_at < Carbon::parse('2019-03-18 13:30:00')){
                    $booking->china_bankslip_path = null;
                }
            }

            if($po){
                for($index = 0;$index < count($po); $index++){
                    $po[$index] = Storage::url($po[$index]->image_path);
                }
                $booking->user_po_path = $po;
            }

            if($invoice){
                for($index = 0;$index < count($invoice); $index++){
                    $invoice[$index] = Storage::url($invoice[$index]->invoice_path);
                }
                $booking->invoice_path = $invoice;
            }

            $booking->service_charge = 0;
            if($booking){
                if ($booking->amount < 10000 && ($booking->term === 'x2_cash' || $booking->term === 'x2_cheque' || $booking->term === 'x2_ba')) {
                    $booking->service_charge = 20;
                }
            }

            // set timeout
            $date1 = new DateTime($booking->created_at);
            $date2 = new DateTime();
            $time_in_seconds = SettingCredit::orderby('updated_at','desc')->first()->time_limit;
            $difference_in_seconds = ($date1->format('U') + $time_in_seconds) - ($date2->format('U'));
            $booking->timeout = $difference_in_seconds; 
            $booking->marking = $booking->user->marking;

            if (!$booking){
                return response()->json(['success'=>false, 'message'=>'not found'], 404);
            }

            return $booking;
        }
        else{
            return response()->json(['success'=>false, 'message'=>'Booking not found'], 404);
        }
    }

	public function adminShow($id)
    {   
		$booking = Booking::where('id', $id)->firstOrFail();

        
        $user_bankslip = $booking->userBankSlip()->first();
        $china_bankslip = $booking->chinaBankSlip()->get();

        //temporary block
        if($booking->created_at < Carbon::parse('2019-03-18 13:30:00')){
            $china_bankslip = null;
        }

        $po = $booking->purchaseOrder()->get();
        $invoice = $booking->invoice()->get();

		if($booking){
            if ($user_bankslip){
                $booking->user_bankslip_path = Storage::url($user_bankslip->bankslip_path);
                $booking->reject_reason = $user_bankslip->reject_reason;
                $date1 = new DateTime($user_bankslip->updated_at);
            }

            if($china_bankslip){
                for($index = 0;$index < $booking->chinaBankSlip()->count();$index++){
                    $china_bankslip[$index] = Storage::url($china_bankslip[$index]->china_bank_slip_path);
                }
                $booking->china_bankslip_path = $china_bankslip;
            }

            if($po){
                for($index = 0;$index < count($po); $index++){
                    $po[$index] = Storage::url($po[$index]->image_path);
                }
                $booking->user_po_path = $po;
            }

            if($invoice){
                for($index = 0;$index < count($invoice); $index++){
                    $invoice[$index] = Storage::url($invoice[$index]->invoice_path);
                }
                $booking->invoice_path = $invoice;
            }

            $booking->service_charge = 0;
            if($booking){
                if ($booking->amount < 10000 && ($booking->term === 'x2_cash' || $booking->term === 'x2_cheque' || $booking->term === 'x2_ba')) {
                    $booking->service_charge = 20;
                }
            }

            // set timeout
            $date1 = new DateTime($booking->created_at);
            $date2 = new DateTime();
            $time_in_seconds = SettingCredit::orderby('updated_at','desc')->first()->time_limit;
            $difference_in_seconds = ($date1->format('U') + $time_in_seconds) - ($date2->format('U'));
            $booking->timeout = $difference_in_seconds; 
            $booking->marking = $booking->user->marking;

            if (!$booking){
                return response()->json(['success'=>false, 'message'=>'not found'], 404);
            }
            return $booking;
		}
    }

    public function store(Request $request)
    {
        $term = $request->input('term');
        $amount = $request->input("amount");    // in RMB
        $rates = Rate::orderby('updated_at','desc')->first();
        $creditLimit = SettingCredit::orderby('updated_at','desc')->first();
        $taxrate = SettingTaxRate::latest()->first()->tax_rate;
        $billingChargeRate = SettingBillingCharge::latest()->first()->billing_charge_rate;

		if (!$creditLimit){
			return response()->json("Credit limit not set, please contact admin", 405);
		}

        if($amount > $creditLimit->rmb_credit_limit){
            return response()->json("Exceed credit limit, need approved from admin", 401);
        }

        $user = Auth::user(); 
        $rate = 1; // default rate to 1 


        switch ($term) {
            case "x1_cash":
                $rate = $rates->x1_cash;
                break;
            case "x1_cheque":
                $rate = $rates->x1_cheque;
                break;
            case "x1_ba":
                $rate = $rates->x1_ba;
                break;
            case "x2_cash":
                $rate = $rates->x2_cash;
                break;
            case "x2_cheque":
                $rate = $rates->x2_cheque;
                break;
            case "x2_ba":
                $rate = $rates->x2_ba;
                break;
            default:
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid input',
                ], 422);
                break;
        }
        $svcharge = 0;
        // Service charge (RMB) : if amount higher than 10,000 or term x2 no service charge.
        if ($amount < 10000 && ($term == 'x2_cash' || $term == 'x2_cheque' || $term == 'x2_ba')) {
            $svcharge = 20;
        }
       
        $subtotal = round(($amount + $svcharge) / $rate, 2);
        
        // TODO : refactor 
        if ($taxrate !=0){
           $taxAmount = round($subtotal * $taxrate - $subtotal, 2);
        }
        else{
            $taxAmount = 0;
        }
        
        if ($term == 'x2_cash' || $term == 'x2_cheque' || $term == 'x2_ba'){
            $billingChargeAmount = 0;
        }
        else{
            // TODO : billing charge rate to percentage so we do not need to minus amount + svcharge
            $billingChargeAmount = round((($amount / $rate) * $billingChargeRate) - ($amount / $rate), 2);
        }
        
        
 
        $bankin_amount = round($subtotal + $taxAmount + $billingChargeAmount , 2);
        $booking = new Booking();
        $booking->billing_charge = $billingChargeAmount;
        $booking->service_charge = $svcharge;
        $booking->account_name = $request->input('account_name');
        $booking->account_num = $request->input('account_num');
        $booking->bank_name = $request->input('bank_name');
        $booking->bank_branch = $request->input('bank_branch');
        $booking->amount = $request->input('amount');
        $booking->order_no = $request->input('order_no');
        $booking->payment_for = $request->input('payment_for');
        $booking->term = $term;
        $booking->rate_id = $rates->id;
        $booking->rate = $rate; 
        $booking->rmb_book_amount = $request->input('amount'); // BIG TODO : amount change variable name to rmb_book_amount 
        $booking->status = 2; 
        $booking->bia = $bankin_amount; // BID TODO : change bia viariable name 
        // $booking->user_id = $user->id;
        $booking->user()->associate($user);
       

        // The test failed due to ->save() before filling up the information at below

        // TODO : handle RMB, MYR and USD (we can use exchange type: USDtoMYR, RMBtoMYR vise versa to switch case)
        // $booking->rmb_book_pay_method = $request->input('payment_method');
        // $booking->rmb_book_account_name = $request->input('rmb_book_account_name');
        // $booking->rmb_book_acc_no = $request->input('rmb_book_acc_no');
        // $booking->rmb_book_bank_branch = $request->input('rmb_book_bank_branch');
        // $booking->company_name = $request->input('company_name');
        // $booking->company_address = $request->input('company_address');
        // $booking->bank_address = $request->input('bank_address');
        // $booking->swift_code = $request->input('swift_code');
        // $booking->cnap = $request->input('cnap');
        // $booking->term = $request->input('term');

        // $booking->usd_book_amount = $request->input('usd_book_amount');
        // $booking->usd_book_pay_method = $request->input('usd_book_pay_method');
        // $booking->usd_book_company_name = $request->input('usd_book_company_name');
        // $booking->usd_book_company_address = $request->input('usd_book_company_address');
        // $booking->usd_book_swift_code = $request->input('usd_book_swift_code');
        // $booking->usd_book_cnap = $request->input('usd_book_cnap');
        // $booking->usd_book_bank_branch = $request->input('usd_book_bank_branch');
        // $booking->verification_status = $request->input('verification_status');
        // return response()->json($booking, 201);
        $booking->save();
        // return response()->json('error', 400);
        return response()->json($booking, 201);
    }

    public function update(Request $request, $book_id)
    {
        $book_id = Booking::find($book_id);
        $book_id->account_name = $request->input('account_name');
        $book_id->account_num = $request->input('account_num');
        $book_id->bank_name = $request->input('bank_name');
        $book_id->bank_branch = $request->input('bank_branch');
        $book_id->company_name = $request->input('company_name');
        $book_id->company_address = $request->input('company_address');
        $book_id->bank_address = $request->input('bank_address');
        $book_id->swift_code = $request->input('swift_code');
        $book_id->cnap = $request->input('cnap');
        $book_id->save();
 
        return response()->json(['book_id'=>$book_id],200);
    }

    private function uploadbankslip(Request $request, $id)
    {
        $booking = Booking::where('user_id',Auth::user()->id)->where('id',$id)->first();
        
        /* Validation*/
        if (!$booking)
        {
            return response()->json(['message'=>'Access denied'], 403);
        }

        // $validator = Validator::make($request->all(), [
        //     'slip_image'   => 'mimes:jpg,jpeg,bmp,png,xls,xlsx,doc,docx,pdf'
        // ]);

        // if($validator->fails())
        // {
        //     return response()->json(['message'=>'Incorrect format'],400);
        // }

        // $validator = Validator::make($request->all(), [
        //     'slip_image'   => 'max:10000' // image size 
        // ]);

        // if($validator->fails())
        // {
        //     return response()->json(['message'=>'Image too large, upload files up to 3 MB'], 400);
        // }


        if($bankslip_file = $request->input('slip_image'))
        
        {

            $upload_path = (new Base64Uploader())->execute($bankslip_file, 'user_bankslip');
            
            if($upload_path){
                $user_bankslip = $booking->userBankSlip()->first();
            
                // if user bankslip not exist, create new one 
                if(!$user_bankslip){
                    $user_bankslip = new UserBankSlip;
                }
                $user_bankslip->booking_id = $booking->id;
                $user_bankslip->bankslip_path =  'user_bankslip'.'/'.$upload_path;
                $user_bankslip->transfer_amount = null;
                $user_bankslip->save();
    
    
                return response()->json(['message'=>"Success"],200);   
            }
            else{
                return response()->json(['message' => 'File not uploaded. Please contact support'], 400);
            }


        } 
        else {
            return response()->json(['message' => 'No file detected'], 400);
        } 
    }

    public function updateBankSlipAmount(Request $request, $id){
        $this->uploadbankslip($request, $id);
        $booking = Booking::where('user_id',Auth::user()->id)->where('id',$id)->first();
        $user_bankslip = $booking->userBankSlip()->first();

        if(!$user_bankslip){
            return response()->json(["message"=> "not found"],400);
        }
        
        // validate transfer amount exist 
        if(!$request->input('transfer_amount')){
            return response()->json(['message' => 'Please input amount'], 400);
        }
		
		// update booking status 
		$booking->status = 3;
		$booking->admin_status = 2; 
		$booking->save();

        $user_bankslip->transfer_amount = $request->input('transfer_amount');
        $user_bankslip->save();
        return response()->json(["success"=>true],200);
    }

    private function uploadPurchaseOrder(Request $request, $id)
    {
        $booking = Booking::where('user_id',Auth::user()->id)->where('id',$id)->first();

        /* Validation */
            if (!$booking)
            {
                return response()->json(['message'=>'Access denied'], 403);
            }

            // $validator = Validator::make($request->all(), [
            //     'file'   => 'mimes:jpg,jpeg,bmp,png,xls,xlsx,doc,docx,pdf'
            // ]);

            // if($validator->fails())
            // {
            //     return response()->json(['message'=>'Incorrect format'],400);
            // }

            // $validator = Validator::make($request->all(), [
            //     'file'   => 'max:10000'
            // ]);

            // if($validator->fails())
            // {
            //     return response()->json(['message'=>'File too large, upload files up to 3 MB'], 400);
            // }

            if(!$user_input_file = $request->input('images'))
            {
                return response()->json(['message' => 'No file detected'], 404);
            }
        /* End Validation */
        foreach($request->input('images') as $file){
            $filename = (new Base64Uploader())->execute($file, 'purchase_order');
            $user_po = new PurchaseOrder;
            $user_po->image_path = 'purchase_order/'.$filename;
            $user_po->booking_id = $booking->id;
            $user_po->save();
        }

        $booking->status = 6;
		// $booking->admin_status = 7; 
        $booking->admin_status = 6; 
        $booking->save();

        return response()->json(['message'=>'Success'],200);
    }

    public function showPurchaseOrder($id){
        $booking = Booking::where('id',$id)->first();
        $user_po = $booking->purchaseOrder()->first();

        if($user_po){
            return response()->json(['user_po_path'=> $user_po->image_path ],200);
        }

        return response()->json(['message'=> 'waiting customer to upload their po'], 200);
    }

    public function delete(Booking $book_id)
    {
        $booking = Booking::where('user_id', Auth::user())->where('id', $book_id)->firstOrFail();
        $booking->delete($book_id);
        return response()->json($book_id, 204);
    }

     public function CancelledBookings()
     {
         $bookings = Booking::where('is_cancel', 1)->paginate(10);
         foreach ($bookings as $booking) {
             // set timeout
             $date1 = new DateTime($booking->created_at);
             $date2 = new DateTime();
             $time_in_seconds = SettingCredit::orderby('updated_at','desc')->first()->time_limit;
             $difference_in_seconds = ($date1->format('U') + $time_in_seconds) - ($date2->format('U'));
             $booking->timeout = $difference_in_seconds;

             // TODO : you can make it better
             if($difference_in_seconds < 0 ){
                 $booking->timeout = 0;
             }

             // TODO : transfer_amount change name to bia
             $booking->transfer_amount = $booking->bia;

             $term = $booking->term;
             if ($booking->term == "x2_cash" || $booking->term == "x2_cheque" || $booking->term == "x2_ba"){
                 $booking->track_status = "(". $booking->admin_status ."/6)";
             }
             else{
                 $booking->track_status = "(". $booking->admin_status ."/7)";
             }

             $booking->marking = $booking->user->marking;
             $booking->status_desc = "Booking Canclled";
         }
         return $bookings;

     }

     public function cancelBooking($book_id)
     {
         $booking = Booking::findOrFail($book_id);
         $booking->is_cancel = 1;
         if($booking->save()){
             return response()->json(['message'=> 'booking cancelled'], 200);
         }

     }

    public function calculation(Request $request)
    {
        $amount = $request->input('amount');
        $term = $request->input('term');
        $china_beneficiary = $request->input('china_beneficiary');
        $order_no = $request->input('order_no');
        $payment_for = $request->input('payment_for');
        $rates = Rate::orderby('updated_at','desc')->first();
        $marking = $user = Auth::user()->marking;
        $taxrate = SettingTaxRate::latest()->first()->tax_rate;
        $billingChargeRate = SettingBillingCharge::latest()->first()->billing_charge_rate;

        $creditLimit = SettingCredit::orderby('updated_at','desc')->first();

		if (!$creditLimit){
			return response()->json("Credit limit not set, please contact admin", 405);
		}

        if($amount > $creditLimit->rmb_credit_limit){
            return response()->json(["message" => "Exceed credit limit, please contact our sales team for larger quantitiy"], 400);
        }
 
        switch ($term) {
         case "x1_cash":
             $rate = $rates->x1_cash;
             $payment_method = "CASH";
             break;
         case "x1_cheque":
             $rate = $rates->x1_cheque;
             $payment_method = "CHEQUE";
             break;
         case "x1_ba":
             $rate = $rates->x1_ba;
             $payment_method = "BA";
             break;
         case "x2_cash":
             $rate = $rates->x2_cash;
             $payment_method = "CASH";
             break;
         case "x2_cheque":
             $rate = $rates->x2_cheque;
             $payment_method = "CHEQUE";
             break;
         case "x2_ba":
             $rate = $rates->x2_ba;
             $payment_method = "BA";
             break;
         default:
             return response()->json([
                 'success' => false,
                 'message' => 'Invalid input',
             ], 422);
             break;
         }
        $svcharge = 0;
         if ($amount < 10000 && ($term === 'x2_cash' || $term === 'x2_cheque' || $term === 'x2_ba')) {
             $svcharge = 20;
         }
        
         $subtotal = round(($amount + $svcharge) / $rate,2);
         
         // TODO : refactor 
         if ($taxrate !=0){
            $taxAmount = round($subtotal * $taxrate - $subtotal,2);
         }
         else{
             $taxAmount = 0;
         }
         
        if ($term == 'x2_cash' || $term == 'x2_cheque' || $term == 'x2_ba'){
            $billingChargeAmount = 0;
        }
        else{
            // TODO : billing charge rate to percentage so we do not need to minus amount + svcharge
            $billingChargeAmount = round((($amount / $rate) * $billingChargeRate) - ($amount / $rate), 2);
        }
        
         $bankin_amount = round($subtotal + $taxAmount + $billingChargeAmount , 2);
 
         return response()->json([
             'date' => date('Y-m-d'),
             'order_no' => $order_no,
             'payment_for' => $payment_for,
             'marking' => $marking,
             'payment_method' => $payment_method,
             'china_beneficary' => $china_beneficiary,
             'amount' => $amount,
             'service_charge' => $svcharge,
             'rate' => $rate,
             'subtotal' => $subtotal,
             'taxAmount' => $taxAmount,
             'billingChargeAmount' => $billingChargeAmount,
             'bankin_amount' => $bankin_amount,
             'bank_name'=> $request->input('bank_name'),
             'bank_branch'=> $request->input('bank_branch'),
             'acc_name' => $request->input('acc_name'),
             'acc_no' => $request->input('acc_no')
         ], 200);
    }

    public function approveBankSlip(Request $request, $book_id)
    {
        $booking = Booking::where('id',$book_id)->first();

        if (!$booking)
        {
            return response()->json(['message'=>'Booking not found'], 400);
        }

        if(!$userBankSlip = UserBankSlip::where('booking_id',$booking->id)->first())
        {
            return response()->json(['message'=>'User bankslip not found'], 400);   
        }

        // Rejected bankslip cannot be approve again
        // if($userBankSlip->is_reject == 1)
        // {
        //     return response()->json(['message'=>'Bankslip already rejected'],200);    
        // }

        $userBankSlip->is_approve = 1;
        $userBankSlip->is_reject = 0;
        $userBankSlip->save();

        // update booking status 
		$booking->status = 4;
        if($booking->term !== "x1_ba" || $booking->term !== "x2_cheque"){
    		$booking->admin_status = 3;
            // TODO : Add notification message to user

        }
        else{
            $booking->admin_status = 5;
            // TODO : Add notification message to user

        }
        $booking->save();

        
        return response()->json(['message'=>'Success'],200);
    }

    public function rejectBankSlip(Request $request, $book_id)
    {
        $booking = Booking::where('id',$book_id)->first();
        if (!$booking)
        {
            return response()->json(['message'=>'Access denied'], 403);
        }

        if(!$userBankSlip = UserBankSlip::where('booking_id',$booking->id)->first())
        {
            return response()->json(['message'=>'Access denied'], 403);
        }

        // approved bankslip cannot be reject again
        if($userBankSlip->is_approve == 1)
        {
            return response()->json(['message'=>'Bankslip already approved'],200);    
        }

        $userBankSlip->is_reject = 1;
        $userBankSlip->reject_reason = $request->input('reject_reason');
        $userBankSlip->save();

        // update booking status 
		$booking->status = 2; // upload user bankslip 
		$booking->admin_status = 1; // user booking  
        $booking->save();

        return response()->json(['message'=>'Success'],200);
    }
    
    public function uploadInvoice(Request $request, $id)
    {
        $booking = Booking::where('id',$id)->first();

        /* Validation */
            if (!$booking)
            {
                return response()->json(['message'=>'Access denied'], 403);
            }

            $validator = Validator::make($request->all(), [
                'invoice_path'   => 'mimes:jpg,jpeg,bmp,png,xls,xlsx,doc,docx,pdf'
            ]);

            if($validator->fails())
            {
                return response()->json(['message'=>'Incorrect format'],400);
            }

            $validator = Validator::make($request->all(), [
                'invoice_path'   => 'max:10000'
            ]);

            if($validator->fails())
            {
                return response()->json(['message'=>'Image too large, upload files up to 3 MB'], 400);
            }

            if(!$input_file = $request->file('file'))
            {
                return response()->json(['message'=>'No file detected'], 400);
            }
        /* End Validation */

        $filename = $input_file->getClientOriginalName();
        $ext = $input_file->getClientOriginalExtension();

        $unique_name = 'invoice' . md5($filename. time());
        $unique_file_url = $unique_name. '.' .$ext;
        $upload_path = Storage::disk('public')->putFileAs(
            'invoice', $input_file, $unique_file_url, 'public'
        );
        
        $invoice = new Invoice;
        $invoice->invoice_path = $upload_path;
        // TODO : amount 
        $invoice->amount = 0;
        $invoice->booking_id = $booking->id;
        $invoice->save();

        return response()->json(['message'=>"Success"],200);
    }

    public function confirmSupplier(Request $request, $id)
    {
        $booking = Booking::where('id', $id)->firstOrFail();
        $booking->status = 4; // processing transfer 
		$booking->admin_status = 5;  // upload china bankslip 
        
        if($booking->save()){
            // $userNotification = new Notification;
            // $userNotification->detail = "Supplier booking report for booking " . $booking->id . " is completed.";
            // $userNotification->link = "/booking/" . $booking->id . "/transfer";
            // $userNotification->user_id = $booking->user_id;
            // $userNotification->save();
            return response()->json(['message'=>"Success"],200);
        }
    }
    
    public function confirmPurchaseOrder($id, Request $request){
        $this->uploadPurchaseOrder($request, $id);
        $booking = Booking::where('user_id',Auth::user()->id)->where('id',$id)->first();

        $purchase_order = $booking->purchaseOrder()->first();

        if(!$purchase_order){
            return response()->json(["message"=> "Please upload your purchase order"],400);
		}
        $booking->status = 6;  // wait invoice
        $booking->admin_status = 6; // upload invoice
        $booking->save();

        return response()->json($purchase_order,200);
    }

    public function confirmInvoice(Request $request, $id)
    {
        $booking = Booking::where('id', $id)->firstOrFail();

        $invoice = $booking->invoice()->first();

        if(!$invoice){
            return response()->json(["message"=> "Please upload your invoice"],400);
        }

        $booking->status = 7; // completed
		$booking->admin_status = 7;  // completed
        
        if($booking->save()){
            return response()->json(['message'=>"Success"],200);
        }
    }

    public function adminShowCompletedOrders()
    {
        $bookings = Booking::select('id','created_at','user_id','rate','amount', 'bia', 'admin_status')
               ->where('admin_status', 7)
               ->orderBy('id', 'desc')
               ->get();
               
        foreach ($bookings as $booking) {
            $booking->id;
            $booking->created_at;
            $booking->marking = $booking->user->marking;
            $booking->rate;
            $booking->amount;
            $booking->bia;
            $booking->admin_status = "(". $booking->admin_status ."/7)";;
        }
        return $bookings;
    }

}
