<?php

namespace App\Http\Controllers;

use App\Orders;
use App\Modelmaster;
use App\JobWorkDetail;
use App\JobWork;
use App\SaleableitemRelation;
use App\CustomerMaster;
use App\Typemaster;
use App\SalesBill;
use App\SalesBillDetail;
use App\PaymentReceived;
use App\Inquiry;
use Lang;
use Mail;
use Redirect;
use Validator;
use URL;
use View;
use DB;
use File;
use Auth;
use Image;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class FrontController extends Controller {

    /**
     * display classes.
     *
     * @return View
     */
    public function getHome() {
        return view('home');
    }

    public function underConstruction() {
        return view('underConstruction');
    }

    public function getAbout() {
        return view('about');
    }

    public function getContact() {
        $app_setting = DB::table(appsettings)->get();

        return view('contact', compact('app_setting'));
    }

    public function getDashboard() {
        return view('dashboard');
    }

    public function getHistory() {
        if (Auth::guard('customer')->check()) {
            $user = Auth::guard('customer')->user();
            // $orders = Orders::where('ordCustID', $user->pmID)
            //         ->with(['Brand', 'Customer', 'Model'])
            //         ->orderBy('ordID','DESC')
            //         ->get();
            $commonData = new \App\Library\RPCommanData();
            $acy_id = $commonData->get_active_accounting_year();
            $outstanding = $commonData->Outstanding_Amount_bycust($user->pmID, 0, $acy_id);
            return view('history', compact('outstanding'));
        } else {
            return Redirect::route('home');
        }
    }

    public function postInquiry(Request $request) {

        $eqName = $request->get('eqName');
        $eqEmail = $request->get('eqEmail');
        $eqMobile = $request->get('eqMobile');
        $eqMessage = $request->get('eqMessage');
        $success = true;
        $error = array();

        if ($eqName == '') {
            $success = false;
        }
        if ($eqEmail == '') {
            $success = false;
        }
        if ($eqMobile == '') {
            $success = false;
        }
        if ($eqMessage == '') {
            $success = false;
        }

        $return = array('success' => false, 'message' => 'Please fill all fields.');

        if ($success) {
            $res = new Inquiry();
            $res->eqName = $request->get('eqName');
            $res->eqEmail = $request->get('eqEmail');
            $res->eqMobile = $request->get('eqMobile');
            $res->eqMessage = $request->get('eqMessage');
            $res->eqDate = date('Y-m-d');
            if ($res->save()) {

                $bodymessage = file_get_contents(asset('assets/email_template/email_template_inquiry.html'));
                $bodymessage_admin = file_get_contents(asset('assets/email_template/email_template_inquiry_admin.html'));

                $logo_url = asset('assets/email_template/Company-Logo.png');
                $icon_url = asset('assets/email_template/Company-icon.png');
                $facebook_url = asset('assets/email_template/facebook.jpg');
                $email_url = asset('assets/email_template/email.jpg');
                $website_url = asset('assets/email_template/website.jpg');

                $inqdata = '<p style="font-family: sans-serif; font-size: 18px; font-weight: normal; margin: 0; Margin-bottom: 15px;"><strong>Name:</strong> ' . $eqName . '</p>';
                $inqdata .= '<p style="font-family: sans-serif; font-size: 18px; font-weight: normal; margin: 0; Margin-bottom: 15px;"><strong>Email:</strong> ' . $eqEmail . '</p>';
                $inqdata .= '<p style="font-family: sans-serif; font-size: 18px; font-weight: normal; margin: 0; Margin-bottom: 15px;"><strong>Mobile:</strong> ' . $eqMobile . '</p>';
                $inqdata .= '<p style="font-family: sans-serif; font-size: 18px; font-weight: normal; margin: 0; Margin-bottom: 15px;"><strong>Message:</strong> ' . $eqMessage . '</p>';

                $subject_customer = 'Your enquiry has been successfully sent to the ' . SITE_NAME;
                $subject_admin = 'New Inquiry From ' . SITE_NAME . ' Website';

                $variablese = array(
                    '{{rp_businessname}}' => ucfirst($eqName),
                    '{{rp_inquiry_data}}' => $inqdata,
                    '{{company_logo}}' => $logo_url,
                    '{{company_icon}}' => $icon_url,
                    '{{company_email}}' => $email_url,
                    '{{company_name}}' => SITE_NAME,
                    '{{company_website}}' => $website_url,
                    '{{company_mail}}' => company_email,
                    '{{company_website_link}}' => company_website,
                );
                $message = str_replace(array_keys($variablese), array_values($variablese), $bodymessage);
                $message_admin = str_replace(array_keys($variablese), array_values($variablese), $bodymessage_admin);

                $headers = '';
                $headers .= 'Content-Type: text/html; charset=UTF-8' . PHP_EOL;
                $headers .= 'From: ' . SITE_NAME . ' <' . header_email . '>' . PHP_EOL;

                $send = mail($eqEmail, $subject_customer, $message, $headers);
                $send = mail(admin_email, $subject_admin, $message_admin, $headers);

                $return = array('success' => true, 'message' => 'Thankyou for connecting us. Your inquery successfully submited.');
            }
        }

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

    public function custOutstanding() {
        if (Auth::guard('customer')->check()) {
            $user = Auth::guard('customer')->user();

            $commonData = new \App\Library\RPCommanData();
            $acy_id = $commonData->get_active_accounting_year();
            $outstanding = $commonData->Outstanding_Amount_bycust($user->pmID, 0, $acy_id);

            return view('cust_outstanding', compact('outstanding'));
        } else {
            return Redirect::route('home');
        }
    }

    /*
     * Pass data through ajax call
     */

    public function data(Request $request) {
        $user = Auth::guard('customer')->user();
        $data = JobWork::select('jwID', 'jwNum', 'jwDate', 'jwDispacheDate', 'jwPmID', 'jwType', 'jwTotal')
                ->has('JobWorkDetail')
                ->where('jwPmID', $user->pmID);

        $commonData = new \App\Library\RPCommanData();
        $activeYear = $commonData->get_active_accounting_year();

        $url = asset('storage/uploads/job/');
        $jobUrl = asset('storage/uploads/job/' . $activeYear . '/thumb/');

        $destinationPath = storage_path() . '/uploads/job/' . $activeYear . '/thumb/';

        return Datatables::of($data)
                        ->editColumn('jwDate', function($data) {
                            return Convert_Date_To_DD_MM_YYYY($data->jwDate);
                        })
                        ->editColumn('jwDispacheDate', function($data) {
                            return isset($data->jwDispacheDate) && !empty($data->jwDispacheDate) ? Convert_Date_To_DD_MM_YYYY($data->jwDispacheDate) : '-';
                        })
                        ->editColumn('JobWorkDetail', function($data) {
                            $actions = $data->JobWorkDetail[0]->jwdItemName;
                            return $actions;
                        })
                        ->addColumn('frontImage', function($data) use($jobUrl, $destinationPath, $url) {
                            $imagename = isset($data->JobWorkDetail[0]->jwdFrontImage) && !empty($data->JobWorkDetail[0]->jwdFrontImage) ? $data->JobWorkDetail[0]->jwdFrontImage : 'Noimage.jpg';
                            if (file_exists($destinationPath . $imagename)) {
                                $imagename = $jobUrl . '/' . $imagename;
                            } else {
                                $imagename = $url . '/' . 'Noimage.jpg';
                            }
                            return '<img src="' . $imagename . '" width="70px;" />';
                        })
                        ->addColumn('backImage', function($data) use($jobUrl, $destinationPath, $url) {
                            $imagename = isset($data->JobWorkDetail[0]->jwdBackImage) && !empty($data->JobWorkDetail[0]->jwdBackImage) ? $data->JobWorkDetail[0]->jwdBackImage : 'Noimage.jpg';
                            if (file_exists($destinationPath . $imagename)) {
                                $imagename = $jobUrl . '/' . $imagename;
                            } else {
                                $imagename = $url . '/' . 'Noimage.jpg';
                            }
                            return '<img src="' . $imagename . '" width="70px;" />';
                        })
                        ->editColumn('jwTotal', function($data) {
                            $actions = $data->JobWorkDetail[0]->jwdQty;
                            return $actions;
                        })
                        ->rawColumns(['frontImage', 'backImage'])
                        ->make(true);
    }

    public function getPurchaseHistory(Request $request) {

        if (Auth::guard('customer')->check()) {
            $user = Auth::guard('customer')->user();

            $data = SalesBill::with('Sbjob')->select('sbID', 'sbDate', 'sbNum', 'sbGrandTotal', 'sbJobId')
                    ->where('sbMainType', '1')
                    ->where('sbCustomerID', $user->pmID);

            $totalAmount = SalesBill::where('sbMainType', '1')->where('sbCustomerID', $user->pmID)->sum('sbGrandTotal');

            return Datatables::of($data)
                            ->editColumn('sbDate', function($data) {
                                return Convert_Date_To_DD_MM_YYYY($data->sbDate);
                            })
                            ->editColumn('sbGrandTotal', function($data) {
                                return number_format($data->sbGrandTotal, 2, '.', '');
                            })
                            ->editColumn('Sbjob', function($data) {
                                return isset($data->Sbjob->jwNum) && !empty($data->Sbjob->jwNum) ? $data->Sbjob->jwNum : '-';
                            })
                            ->addColumn('actions', function($data) {
                                $actions = '<a href="javascript:void(0)" title="View More Detail" data-id="' . $data->sbID . '" class="btn btn-sm viwemore btn-icon btn-info button_margin" >View</a>';
                                return $actions;
                            })
                            ->rawColumns(['actions'])
                            ->with([
                                "totalAmount" => number_format($totalAmount, 2, '.', ''),
                            ])
                            ->make(true);
        }
    }

    public function getPaymentHistory(Request $request) {

        if (Auth::guard('customer')->check()) {
            $user = Auth::guard('customer')->user();

            $data = PaymentReceived::with('PaymentMode')->select('prID', 'prDate', 'prNum', 'prAmount', 'prPaymentMode')
                    ->where('prPmID', $user->pmID);

            $totalAmount = PaymentReceived::where('prPmID', $user->pmID)->sum('prAmount');

            return Datatables::of($data)
                            ->editColumn('prDate', function($data) {
                                return Convert_Date_To_DD_MM_YYYY($data->prDate);
                            })
                            ->editColumn('PaymentMode', function($data) {
                                return $data->PaymentMode->pymName;
                            })
                            ->editColumn('prAmount', function($data) {
                                return number_format($data->prAmount, 2, '.', '');
                            })
                            ->addColumn('actions', function($data) {
                                $actions = '<a href="javascript:void(0)" title="View More Detail" data-id="' . $data->prID . '" class="btn btn-sm viwePayment btn-icon btn-info button_margin" >View</a>';
                                return $actions;
                            })
                            ->with([
                                "totalAmount" => number_format($totalAmount, 2, '.', ''),
                            ])
                            ->rawColumns(['actions'])
                            ->make(true);
        }
    }

    public function getOrder() {
        $brand = DB::table(brands)->where('brType', '1')->where('brStatus', '1')->get();
        $brands = array('' => 'Select Brand');
        foreach ($brand as $data) {
            $brands[$data->brID] = $data->brName;
        }
        return view('order', compact('brands'));
    }

    public function extraItems() {
        $brand = DB::table(brands)->where('brType', '2')->get();
        $brands = array('' => 'Select Brand');
        foreach ($brand as $data) {
            $brands[$data->brID] = $data->brName;
        }
        return view('extra', compact('brands'));
    }

    public function postOrder(Request $request) {
        //chech validation

        $jwOrderType = $request->get('jwOrderType');
        $jwOrderType = isset($jwOrderType) && $jwOrderType == 2 ? 2 : 1;
        $brand_Image_upload = $request->get('brand_Image_upload');
        $brand_Image_upload = isset($brand_Image_upload) && $brand_Image_upload == 2 ? 2 : 1;

        if (Auth::guard('customer')->check()) {
            $validator = Validator::make($request->all(), [
                        'jwdBrandID' => 'required',
                        'jwdItemId' => 'required',
                        'jwdQty' => 'required',
            ]);

            $user = Auth::guard('customer')->user();

            // If validation fails, we'll exit the operation now.
            if ($validator->fails()) {
                return Redirect::back()->withInput()->withErrors($validator);
            }

            $commonData = new \App\Library\RPCommanData();
            $auto_bill = $commonData->get_option('auto_bill', 'no');
            $auto_bill_type = $commonData->get_option('auto_bill_type', 'retail');
            $job_delivery_days = $commonData->get_option('job_delivery_days', '3');
            $folder_structure_enable = $commonData->get_option('folder_structure_enable', 'no');
            $stock_update_after = $commonData->get_option('stock_update_after', 'job_add');
            $job_number_format = $commonData->get_option('job_number_format', 'default');
            $check_outstanding = $commonData->get_option('check_outstanding', 'no');
            $activeYear = $commonData->get_active_accounting_year();
            $folderNameJob = '';

            DB::beginTransaction();
            try {

                $customerData = CustomerMaster::with('Ccity')->where('pmID', $user->pmID)->first();

                if ($check_outstanding == 'yes') {
                    if (isset($customerData) && !empty($customerData)) {
                        if ($customerData->pmOutstandingLimit != 0) {
                            $outstanding = $commonData->check_Outstanding($request, $user->pmID, $customerData->pmInvoceType, $customerData->pmStnplID, $customerData->pmState);
                            if ($customerData->pmOutstandingLimit <= $outstanding) {
                                return Redirect::route('order')->withInput()->with('error', "Outstanding limit is crossed so you can not process the new order.");
                            }
                        }
                    }
                }


                if ($job_number_format == 'custom') {
                    $job_number_start = $commonData->get_option('job_number_start', '10000');
                    $jwNum = $job_number_start + 1;
                } else {
                    $max_job_num = JobWork::select(DB::raw('max(jwNum) as jwNum'))->where(DB::raw('LEFT(jwNum,4)'), date("Y"))->withTrashed()->first();
                    if (isset($max_job_num->jwNum) && !empty($max_job_num->jwNum)) {
                        $jwNum = $max_job_num->jwNum + 1;
                    } else {
                        $jwNum = date("Y") . sprintf("%'.06d", 1);
                    }
                }


//            $res_mdl = Modelmaster::where('mdlID', $request->get('mdlID'))
//                    ->get();
                $downloadAvailable = 1;
                if($jwOrderType == 2){
                    $downloadAvailable = $brand_Image_upload;
                }
                
                $res = new JobWork();
                $res->jwPmID = $user->pmID;
                $res->jwNum = $jwNum;
                $res->jwDate = date('Y-m-d');
                $res->jwTime = date('H:i:s');
                $res->jwDeliveryDate = date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $job_delivery_days . ' days'));
                $res->jwPriorityId = 1;
                $res->jwPrefixID = 2;
                $res->jwType = 1;
                $res->jwTotal = 1;
                $res->jwOrderType = $jwOrderType;
                $res->jwDownloadAvailable = $downloadAvailable;
                $safeNameFront = '';
                $safeNameBack = '';

                $folderName = '/uploads/job/' . $activeYear . '/';
                $thumbFolderName = '/uploads/job/' . $activeYear . '/thumb/';
                $destinationPath = storage_path() . $folderName;
                $thumbDestinationPath = storage_path() . $thumbFolderName;

                if ($file = $request->file('ordImage')) {
                    $fileName = $file->getClientOriginalName();
                    $extensionFront = $file->getClientOriginalExtension() ?: 'png';
                    $safeName = ap_generate_unique_imgname(1,$user->pmID) . '.' . $extensionFront;
                    $allowedfileExtension = array('jpeg', 'jpg', 'png');
                    if (!in_array(strtolower($extensionFront), $allowedfileExtension)) {
                        return Redirect::back()->withInput()->with('error', 'Upload only image file.');
                    }

                    if (!is_dir($destinationPath)) {
                        mkdir($destinationPath, 0777, true);
                    }
                    if (!is_dir($thumbDestinationPath)) {
                        mkdir($thumbDestinationPath, 0777, true);
                    }

                    $img = Image::make($file->getRealPath())->orientate();
                    $img->save($destinationPath . $safeName, 100);

                    $img->resize(null, 150, function ($constraint) {
                        $constraint->aspectRatio();
                    });
                    $img->save($thumbDestinationPath . $safeName, 80);

                    //$file->move($destinationPath, $safeName);

                    $safeNameFront = $safeName;
                }

                if ($file = $request->file('ordImage2')) {
                    $fileName = $file->getClientOriginalName();
                    $extensionBack = $file->getClientOriginalExtension() ?: 'png';
                    $safeName = ap_generate_unique_imgname(2,$user->pmID) . '.' . $extensionBack;
                    $allowedfileExtension = array('jpeg', 'jpg', 'png');
                    if (!in_array(strtolower($extensionBack), $allowedfileExtension)) {
                        return Redirect::back()->withInput()->with('error', 'Upload only image file.');
                    }

                    if (!is_dir($destinationPath)) {
                        mkdir($destinationPath, 0777, true);
                    }

                    if (!is_dir($thumbDestinationPath)) {
                        mkdir($thumbDestinationPath, 0777, true);
                    }

                    $img = Image::make($file->getRealPath())->orientate();
                    $img->save($destinationPath . $safeName, 100);

                    $img->resize(null, 150, function ($constraint) {
                        $constraint->aspectRatio();
                    });
                    $img->save($thumbDestinationPath . $safeName, 80);
                    //$file->move($destinationPath, $safeName);

                    $safeNameBack = $safeName;
                }

                $jwNumNew = $commonData->mp_number_unique($jwNum, 'job');

                if ($safeNameFront != '') {
                    $oldName = $safeNameFront;
                    $newName = $jwNumNew . '-1' . 'F.' . $extensionFront;
                    rename($destinationPath . $oldName, $destinationPath . $newName);
                    rename($thumbDestinationPath . $oldName, $thumbDestinationPath . $newName);
                    $safeNameFront = $newName;
                }

                if ($safeNameBack != '') {
                    $oldName = $safeNameBack;
                    $newName = $jwNumNew . '-1' . 'B.' . $extensionBack;
                    rename($destinationPath . $oldName, $destinationPath . $newName);
                    rename($thumbDestinationPath . $oldName, $thumbDestinationPath . $newName);
                    $safeNameBack = $newName;
                }
                $res->jwNum = $jwNumNew;

                if ($res->save()) {
                    if ($job_number_format == 'custom') {
                        $commonData->update_option('job_number_start', $jwNumNew);
                    }
                    $emboss = $request->get('jwdEmboss');
                    $emboss = $emboss == '1' ? ' Emboss ' : '';
                    if ($folder_structure_enable == 'yes') {
                        $folderNameJob .= $jwNum . ' ' . $customerData->pmCompName . ' ' . $customerData->Ccity->city_name . ' ';
                        $folderNameJob .= $request->get('jwdBrandName') . ' ' . $request->get('jwdItemName') . ' ' . $request->get('jwdSizeName') . ' ' . $request->get('jwdColorName') . $emboss . ' - ' . $request->get('jwdQty');
                    }

                    $jobDetail = [
                        'jwdJwID' => $res->jwID,
                        'jwdItemNo' => $jwNum . '-' . 1,
                        'jwdBrandID' => $request->get('jwdBrandID'),
                        'jwdBrandName' => $request->get('jwdBrandName'),
                        'jwdItemId' => $request->get('jwdItemId'),
                        'jwdItemName' => $request->get('jwdItemName'),
                        'jwdSizeId' => $request->get('jwdSizeId'),
                        'jwdSizeName' => $request->get('jwdSizeName'),
                        'jwdColorId' => $request->get('jwdColorId'),
                        'jwdColorName' => $request->get('jwdColorName'),
                        'jwdQty' => $request->get('jwdQty'),
                        'jwdEmboss' => $request->get('jwdEmboss'),
                    ];
                    if ($safeNameFront != '')
                        $jobDetail['jwdFrontImage'] = $safeNameFront;

                    if ($safeNameBack != '')
                        $jobDetail['jwdBackImage'] = $safeNameBack;

                    JobWorkDetail::insert($jobDetail);

                    if ($stock_update_after == 'job_add') {
                        $jwdSizeId = $request->get('jwdSizeId');
                        $typeID = $commonData->getParentType($jwdSizeId);

                        $get_Items = SaleableitemRelation::select('sarStock', 'sarID')->where('sarSamID', $request->get('jwdItemId'))->where('sarSizeID', $typeID)->where('sarClrID', $request->get('jwdColorId'))->first();

                        if (isset($get_Items) && !empty($get_Items)) {
                            $updateStock['sarStock'] = $get_Items->sarStock - $request->get('jwdQty');
                            DB::table(saleabletypecolorrelation)->where('sarID', $get_Items->sarID)->update($updateStock);
                        }
                    }

                    $jobWork = ['jwTotal' => $request->get('jwdQty'), 'jwFolderName' => $folderNameJob];
                    JobWork::where('jwID', $res->jwID)->update($jobWork);

                    if ($auto_bill == 'yes') {
                        if ($auto_bill_type == 'retail') {
                            $commonData->generateAutoRetail($request, $res->jwID, 0, $res->jwDate, $user->pmID);
                        }
                    }
                    DB::commit();
                    return Redirect::route('history')->with('success', 'Order placed successfully.');
                }
            } catch (\Exception $e) {
                DB::rollback();
                Log::info($e);
                if ($jwOrderType == '2')
                    return Redirect::route('extraItems')->withInput()->with('error', 'Your Internet Connection interrupted.Please try again.');
                else
                    return Redirect::route('order')->withInput()->with('error', 'Your Internet Connection interrupted.Please try again.');
            }
        }
        return Redirect::route('order')->withInput()->with('error', 'Your Internet Connection interrupted.Please try again.');
    }

    public function getPaymentDetail(Request $request) {
        $return = array('success' => false, 'message' => 'Payment Not Found');
        if (Auth::guard('customer')->check()) {
            $user = Auth::guard('customer')->user();

            $prID = $request->get('prID');

            $pbDetail = PaymentReceived::with(['PaymentRecieveDetail'])
                    ->with('PaymentMode')
                    ->where('prPmID', $user->pmID)
                    ->where('prID', $prID);

            $pbDetail = $pbDetail->get();

            if (isset($pbDetail[0]) && !empty($pbDetail[0])) {

                $invoiceDetail = '<table class="table table-striped m-b-none">
                                  <tr>                    
                                    <td><strong>Number</strong></td>
                                    <td>' . $pbDetail[0]->prNum . '</td>
                                    <td><strong>Date</strong></td>
                                    <td>' . $pbDetail[0]->prDate . '</td>    
                                  </tr>
                                  <tr>                    
                                    <td><strong>Amount</strong></td>
                                    <td>' . $pbDetail[0]->prAmount . '</td>    
                                    <td><strong>Mode</strong></td>
                                    <td>' . $pbDetail[0]->PaymentMode->pymName . '</td>    
                                  </tr>';
                if ($pbDetail[0]->prPaymentMode != '2') {
                    $invoiceDetail .= '<tr>                    
                                            <td><strong>Bank Name</strong></td>
                                            <td>' . $pbDetail[0]->prBankName . '</td>
                                            <td><strong>Check Num</strong></td>
                                            <td>' . $pbDetail[0]->prCheckNum . '</td>
                                          </tr>';
                    $invoiceDetail .= '<tr>                    
                                            <td><strong>Check Date</strong></td>
                                            <td>' . Convert_Date_To_DD_MM_YYYY($pbDetail[0]->prCheckDate) . '</td>
                                            <td></td>
                                            <td></td>
                                          </tr>';
                }
                $invoiceDetail .= '<tr>                    
                                            <td><strong>Remarks</strong></td>
                                            <td colspan="3">' . $pbDetail[0]->prRemarks . '</td>
                                          </tr>';
                $invoiceDetail .= '</table>';

                if (isset($pbDetail[0]->PaymentRecieveDetail[0]) && !empty($pbDetail[0]->PaymentRecieveDetail)) {
                    $invoiceDetail .= '<table class="table table-bordered" >
                                    <thead>
                                        <tr>
                                            <th>Invoice No</th>
                                            <th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>';
                    foreach ($pbDetail[0]->PaymentRecieveDetail as $_pbDetail) {
                        $invoiceDetail .= '<tr>';
                        $invoiceDetail .= '<td>' . $_pbDetail->SalseBill->sbNum . '</td>';
                        $invoiceDetail .= '<td>' . $_pbDetail->prdAmount . '</td>';
                        $invoiceDetail .= '</tr>';
                    }
                }
                $invoiceDetail .= '</tbody></table>';

                $return = array('success' => true, 'data' => $invoiceDetail);
            }
        }
        return response()->json($return);
    }

    public function getInvoiceDetail(Request $request) {

        $return = array('success' => false, 'message' => 'Invoice Not Found');

        if (Auth::guard('customer')->check()) {
            $sbID = $request->get('sbID');
            $user = Auth::guard('customer')->user();

            $sbDetail = SalesBill::with('SalesDetail', 'SalesDetail.ItemHsnCode')->where('sbID', $sbID)->where('sbCustomerID', $user->pmID)->get();

            if (isset($sbDetail[0]) && !empty($sbDetail[0])) {
                if ($sbDetail[0]->sbType == '1')
                    $invoiceDetail = $this->viewTaxInvoice($sbDetail);
                else
                    $invoiceDetail = $this->viewRetailInvoice($sbDetail);

                $return = array('success' => true, 'data' => $invoiceDetail);
            }
        }

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

    public function viewTaxInvoice($sbDetail) {

        $invoiceDetail = '<table class="table table-striped m-b-none">
                                  <tr>                    
                                    <td><strong>Invoice Number</strong></td>
                                    <td>' . $sbDetail[0]->sbNum . '</td>
                                    <td><strong>Date</strong></td>
                                    <td>' . $sbDetail[0]->sbDate . '</td>    
                                  </tr>
                                  <tr>                    
                                    <td><strong>Remarks</strong></td>
                                    <td colspan="3">' . $sbDetail[0]->sbRemarks . '</td>
                                  </tr>
                              </table>';

        $invoiceDetail .= '<table class="table table-bordered" >
                                    <thead>
                                        <tr>
                                            <th>Brand</th>
                                            <th>Model</th>
                                            <th>Type</th>
                                            <th>Color</th>
                                            <th>Emboss</th>
                                            <th>Qty</th>
                                            <th>Rate</th>
                                            <th>HSN</th>
                                            <th>GST%</th>';
        if ($sbDetail[0]->sbGstMode == '1') {
            $invoiceDetail .= '<th>IGST</th>';
        } else {
            $invoiceDetail .= '<th>CGST</th>';
            $invoiceDetail .= '<th>SGST</th>';
        }
        $invoiceDetail .= '<th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>';

        if (isset($sbDetail[0]->SalesDetail[0]) && !empty($sbDetail[0]->SalesDetail)) {
            foreach ($sbDetail[0]->SalesDetail as $_SalesDetail) {
                // pr($_SalesDetail);
                //  exit;
                $emboss = $_SalesDetail->sbdEmboss == '1' ? 'Yes' : 'No';
                $invoiceDetail .= '<tr>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdBrandName . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdItemName . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdSizeName . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdColorName . '</td>';
                $invoiceDetail .= '<td>' . $emboss . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdQty . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdRate . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->ItemHsnCode->hsnName . '</td>';
                if ($sbDetail[0]->sbGstMode == '1') {
                    $sbdGSTStr = number_format($_SalesDetail->sbdIgstPercent, 2, '.', '') . '%';
                } else {
                    $sbdGSTStr = number_format($_SalesDetail->sbdCgstPercent + $_SalesDetail->sbdCgstPercent, 2, '.', '') . '%';
                }
                $invoiceDetail .= '<td>' . $sbdGSTStr . '</td>';
                if ($sbDetail[0]->sbGstMode == '1') {
                    $invoiceDetail .= '<td>' . number_format($_SalesDetail->sbdIgstValue, 2, '.', '') . '</td>';
                } else {
                    $invoiceDetail .= '<td>' . number_format($_SalesDetail->sbdCgstValue, 2, '.', '') . '</td>';
                    $invoiceDetail .= '<td>' . number_format($_SalesDetail->sbdSgstValue, 2, '.', '') . '</td>';
                }
                $invoiceDetail .= '<td>' . number_format($_SalesDetail->sbdAmount, 2, '.', '') . '</td>';
                $invoiceDetail .= '</tr>';
            }
        }
        $invoiceDetail .= '</tbody></table>';
        $invoiceDetail .= '<table style="margin-top:25px;" class="table " border="0" >';
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Sub Total</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbTotal, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        if ($sbDetail[0]->sbGstMode == '1') {
            $invoiceDetail .= '<tr>';
            $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
            $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Total IGST</strong></td>';
            $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbTotalIgst, 2, '.', '') . '</strong></td>';
            $invoiceDetail .= '</tr>';
        } else {
            $invoiceDetail .= '<tr>';
            $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
            $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Total SGST</strong></td>';
            $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbTotalSgst, 2, '.', '') . '</strong></td>';
            $invoiceDetail .= '</tr>';
            $invoiceDetail .= '<tr>';
            $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
            $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Total CGST</strong></td>';
            $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbTotalCgst, 2, '.', '') . '</strong></td>';
            $invoiceDetail .= '</tr>';
        }
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Shipping Charge</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbShippingCharge, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Round Off</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbRoundOff, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Grand Total</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbGrandTotal, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Advance Payment</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbAdvancePayment, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        $invoiceDetail .= '</table>';

        return $invoiceDetail;
    }

    public function viewRetailInvoice($sbDetail) {

        $invoiceDetail = '<table class="table table-striped m-b-none">
                                  <tr>                    
                                    <td><strong>Invoice Number</strong></td>
                                    <td>' . $sbDetail[0]->sbNum . '</td>
                                    <td><strong>Date</strong></td>
                                    <td>' . $sbDetail[0]->sbDate . '</td>    
                                  </tr>
                                  <tr>                    
                                    <td><strong>Remarks</strong></td>
                                    <td colspan="3">' . $sbDetail[0]->sbRemarks . '</td>
                                  </tr>
                              </table>';

        $invoiceDetail .= '<table class="table table-bordered" style="margin-top:15px;">
                                    <thead>
                                        <tr>
                                            <th>Brand</th>
                                            <th>Model</th>
                                            <th>Type</th>
                                            <th>Color</th>
                                            <th>Emboss</th>
                                            <th>Qty</th>
                                            <th>Rate</th>
                                            <th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>';

        if (isset($sbDetail[0]->SalesDetail[0]) && !empty($sbDetail[0]->SalesDetail)) {
            foreach ($sbDetail[0]->SalesDetail as $_SalesDetail) {
                // pr($_SalesDetail);
                //  exit;
                $emboss = $_SalesDetail->sbdEmboss == '1' ? 'Yes' : 'No';
                $invoiceDetail .= '<tr>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdBrandName . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdItemName . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdSizeName . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdColorName . '</td>';
                $invoiceDetail .= '<td>' . $emboss . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdQty . '</td>';
                $invoiceDetail .= '<td>' . $_SalesDetail->sbdRate . '</td>';
                $invoiceDetail .= '<td>' . number_format($_SalesDetail->sbdAmount, 2, '.', '') . '</td>';
                $invoiceDetail .= '</tr>';
            }
        }
        $invoiceDetail .= '</tbody></table>';
        $invoiceDetail .= '<table style="margin-top:25px;" class="table " border="0" >';
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Sub Total</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbTotal, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';

        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Plus &nbsp;&nbsp;&nbsp;  (' . number_format($sbDetail[0]->sbVatPercent, 2, '.', '') . ' %)</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbVatValue, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';

        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Shipping Charge</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbShippingCharge, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Round Off</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbRoundOff, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Grand Total</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbGrandTotal, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        $invoiceDetail .= '<tr>';
        $invoiceDetail .= '<td style="width:60%;border-top: none;"></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd;"><strong>Advance Payment</strong></td>';
        $invoiceDetail .= '<td style="border:1px solid #ddd; text-align:right;"><strong>' . number_format($sbDetail[0]->sbAdvancePayment, 2, '.', '') . '</strong></td>';
        $invoiceDetail .= '</tr>';
        $invoiceDetail .= '</table>';

        return $invoiceDetail;
    }

}
