<?php

namespace App\Http\Controllers\backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
use App\Models\Productcategory;
use App\Models\PurchaseDetail;
use App\Models\CustomerRecord;
use App\Models\Customer;
use App\Models\CustomerAccount;
use App\Models\Sale;
use App\Models\SaleDetail;
use App\Models\Product;
use App\Models\ProductionStock;
use Session;
use PDF;

class SalesController extends Controller{

    public function index(Request $request){
        $this->checkpermission('sales-list');
        $show = $request->show;
        if($show != ''){
            $sales = Sale::latest()->paginate($show);
        }else{
            $sales = Sale::latest()->paginate(setting()->ddspinp);
        }
        return view('backend.sales.list', compact('sales'));
    }
    public function condition_sale(Request $request){
        $this->checkpermission('sales-list');
        $show = $request->show;
        if($show != ''){
            $sales = Sale::where('sale_type','Condition')->latest()->paginate($show);
        }else{
            $sales = Sale::where('sale_type','Condition')->latest()->paginate(setting()->ddspinp);
        }
        return view('backend.sales.condition_list', compact('sales'));
    }
    public function create(){
        $this->checkpermission('sales-create');

        $invoice = Sale::where('sale_date',date('Y-m-d'))->latest()->first();
        //return $invoice;
        if($invoice != ''){
            $dt = date('dmy');
            $len = strlen((string)$dt);
            $lv = substr($invoice->invoice_no, $len);
            $inv_no = $dt.$lv + 1;
        }else{
            $inv_no = date('dmy').'1';
        }
        $categories = Productcategory::where('status',1)->get();

        return view('backend.sales.create', compact('categories','inv_no'));
    }
    /*----------Customer Details Section------------------*/
    public function customerList(){
        $customer = Customer::orderBy('name','ASC')->get();
        $data = [];
        foreach($customer as $cus){
            $data[] = $cus->name.', '.$cus->phone;
        }
        return response()->json($data);
    }
    /* customer details section -*/
    public function customerDetails(Request $request){
        $customer = $request->customer;
        /**
         * explode customer name and phone then search the customer for detail information
         */
        $value  = explode(',',$customer);
        $name = $value[0];
        $phone = isset($value[1]) ? $value[1] : null;
       // return response()->json($phone);
        if($name != '' && $phone != ''){
            $data = Customer::where('name',trim($name))->where('phone',trim($phone))->firstOrFail();
        }
        else{
            $data = '';
        }

        return response()->json($data);
    }
    /* product information section from ajax request */
    public function productList2(Request $request){
        $products  = DB::table('production_stocks')
                        ->join('products', 'production_stocks.product_id', '=', 'products.id')
                        ->select('production_stocks.*','products.product_name','products.code')
                        ->where('production_stocks.productcategory_id',$request->type)
                        ->where('production_stocks.now_stock','>',0)
                        ->get();
        return response()->json($products);
    }
    public function productDetails2(Request $request){
           //$products = PurchaseDetail::find($request->id);
           $products  = DB::table('production_stocks')
                        ->join('products', 'production_stocks.product_id', '=', 'products.id')
                        ->join('productcategories', 'production_stocks.productcategory_id', '=', 'productcategories.id')
                        ->join('units', 'production_stocks.unit_id', '=', 'units.id')
                        ->select('production_stocks.*','products.product_name','products.square_foot','products.sale_price', 'products.code','productcategories.name as category_name','units.name as unit_name')
                        ->where('production_stocks.id',$request->id)
                        ->first();
        return response()->json($products);
    }
    public function store(Request $request){
        $closing =  DB::table('cash_closings')->where('closing_date', date('Y-m-d'))->exists();

        if($closing != true){
            //return $request->all();
            $this->validate($request,[
                'customer_name'=>'required',
                'sale_date'=>'required',
            ]);

            $data = $request->except('_token','submit');

            $dt = Carbon::parse($request->sale_date);
            $date = $dt->toDateTimeString();

            $invoice = Sale::where('sale_date',date('Y-m-d',strtotime($request->sale_date)))->latest()->first();
            if($invoice != ''){
                $dt = date('dmy',strtotime($request->sale_date));
                $len = strlen((string)$dt);
                $lv = substr($invoice->invoice_no, $len);
                $inv_no = $dt.$lv + 1;
            }
            else{
                $inv_no = date('dmy',strtotime($request->sale_date)).'1';
            }


            $sale = new Sale();
            $sale->user_id = Auth::id();
            $dt = Carbon::parse($request->sale_date);
            $sale->csale_date = $dt->toDateTimeString();
            $sale->sale_date = $dt->toDateTimeString();
            $sale->invoice_no = $inv_no;
            if($request->customer_id == ''){
                $customer = new Customer();
                $customer->name = $request->customer_name;
                $customer->phone = $request->customer_phone;
                $customer->save();

                $sale->customer_id = $customer->id;
            }else{
                $sale->customer_id = $request->customer_id;
            }

            $sale->sale_type = isset($request->sale_type) ? 'Condition' : 'Sold';
            $sale->total_price = $request->total_price;
            $sale->discount = $request->discount;
            $sale->shiping_cost = $request->other_cost;
            $sale->grand_total_price = $request->grand_total;
            $sale->payment = $request->payment;
            //$sale->payment_by = $request->payment_by;
            if($request->grand_total >= $request->payment){
                $sale->payment_status = 'Due';
            }else{
                $sale->payment_status = 'Paid';
            }
            $sale->due_amount = $request->due;
            $sale->note = $request->note;
            $sale->created_by = Auth::id();
            $sale->save();

            if($request->payment > 0){
                $ca = new CustomerAccount();
                $ca->payment_date = $dt->toDateTimeString();
                $ca->customer_id = $sale->customer_id;
                $ca->sale_id = $sale->id;
                $ca->amount = $request->payment;
                $ca->note = $request->note;
                $ca->save();
            }


            for($i = 0; $i<count($data['product_id']); $i++ ){
                $detail = new SaleDetail();
                $detail->sale_id = $sale->id;
                $detail->customer_id = $sale->customer_id;
                //$detail->purchase_detail_id = $data['purchase_details_id'][$i];
               // $pur = PurchaseDetail::find($data['purchase_details_id'][$i]);
                //$detail->warehouse_id = $pur->warehouse_id;
                $detail->product_id = $data['product_id'][$i];
                $detail->productcategory_id =  $data['category_id'][$i];
                $detail->unit_id =  $data['unit_id'][$i];
                $detail->code =  $data['code'][$i];
                $detail->invoice_no = $sale->invoice_no;

                $dt2 = Carbon::parse($request->sale_date);
                $data['sale_date'] = $dt2->toDateTimeString();

                $detail->sale_date = $data['sale_date'];
                //$detail->height = $data['height'][$i];
                //$detail->width = $data['width'][$i];
               // $detail->size = $data['square_foot'][$i];
                $detail->quantity = $data['ordered_quantity'][$i];
               // $detail->tsqf = $data['tsqf'][$i];
                $detail->unit_price = $data['sale_price'][$i];
                $detail->discount = $data['single_discount'][$i];
                $detail->save();
                /* for decrement stock quantity*/
                //if(!isset($request->sale_type)){
                    DB::table('production_stocks')->where('product_id', '=', $data['product_id'][$i])->decrement('now_stock', $data['ordered_quantity'][$i]);
                    //DB::table('purchase_stocks')->where('product_id', '=', $data['product_id'][$i])->decrement('now_stock', $data['ordered_quantity'][$i]);
               // }
               

            };
            /*-------customer record section----------*/
            $cus = Customer::with('sales')->find($sale->customer_id);

            $record = new CustomerRecord();
            $record->customer_id = $sale->customer_id;
            $record->transaction_date = $dt->toDateTimeString();
            $record->user_id = $sale->user_id;
            $record->total_price = $request->grand_total;
            $record->payment_amount = $request->payment;
            $record->due_amount = $request->due;
            $total_due = $cus->sales->sum('due_amount');
            $record->previous_due = $total_due - $request->due;
            $record->total_due = $total_due;
            $record->note = $request->note;
            $record->message = "Dear Customer ".$cus->name.", your invoice total price is ".$request->grand_total."/=, Payment ".$request->payment."/= Due ".$request->due."/= Previous Due ".$record->previous_due."/= Current Due ".$total_due." Thanks By ".about()->english_name.", ".about()->address;
            $record->created_by = $sale->user_id;
            $record->save();

            /*--------check the sms sending section--------*/
            if(isset($request->sms)){
                //return $request->sms;
                $to = $cus->phone;//"017xxxxxxx,+88016xxxxxxx";
                $token = "daf0cc0b638862523830815f351a8063";
                $message = "Dear customer invoice total:".$record->total_price.',pay:'.$record->payment_amount.',due:'.$record->due_amount.',prev due:'.$record->previous_due.',total due:'.$record->total_due.',Note:'.$record->note.',Date:'.date('d-m-Y',strtotime($record->transaction_date)).'.'.about()->english_name.','.about()->phone;
                $url = "http://api.greenweb.com.bd/api.php?json";
                $data= array(
                    'to'=>"$to",
                    'message'=>"$message",
                    'token'=>"$token"
                ); // Add parameters in key value

                $ch = curl_init(); // Initialize cURL
                curl_setopt($ch, CURLOPT_URL,$url);
                curl_setopt($ch, CURLOPT_ENCODING, '');
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $smsresult = curl_exec($ch);
                //Result
                //echo $smsresult;
                //Error Display
                //echo curl_error($ch);
            }
         //return redirect()->route('sales.show',$sale->id)->with('success','Sales Information Save Successfull');
         return redirect()->back()->with('success','Sales Information Save Successfull');

        }
        else{
            return redirect()->back()->with('error','Woops! After cash closing all transaction has been stoped');
        }
    }
    public function getallpdf(){
        $report = SaleDetail::join('products', 'products.id', '=', 'sale_details.product_id')
            ->select('sale_details.*', 'products.product_name')
            ->get();
        return view('backend.pdfbill.salesbill', compact('report'));
    }
    public function getcustomreport(Request $request){
        $start = $request->start;
        $end = $request->end;
        $report = SaleDetail::join('products', 'products.id', 'sale_details.product_id')
            ->select('sale_details.*', 'products.product_name')
            ->whereBetween('sale_details.sale_date', [$start, $end])
            ->get();
        $pdf = PDF::loadview('backend.pdfbill.allreport', compact('report', 'start', 'end'));
        return $pdf->download('salesreport.pdf');
    }
    public function show($id){
        $sale = Sale::find($id);
        return view('backend.sales.show',compact('sale'));
    }
    public function print($id){
        $sale = Sale::find($id);
        return view('backend.sales.print',compact('sale'));
    }
    public function condition_list(Request $request){
        $this->checkpermission('sales-list');
        $show = $request->show;
        if($show != ''){
            $sales = Sale::where('sale_type','Cancel')->latest()->paginate($show);
        }else{
            $sales = Sale::where('sale_type','Cancel')->latest()->paginate(setting()->ddspinp);
        }
        $conditions = Sale::where('sale_type','Condition')->latest()->get();
        return view('backend.sales.condition_list', compact('sales','conditions'));
    }
    public function condition_change(Request $request){
        $conditions = Sale::where('sale_type','Condition')->latest()->get();
        $sale = Sale::find($request->sale_id);
        return view('backend.sales.condition_change', compact('sale','conditions'));
    }
    public function condition_update(Request $request,$id){
        $sale = Sale::find($id);
        if($request->sale_type == 'Sold'){
            if($request->due_amount >= $request->payment){
                $sale->payment_status = 'Due';
            }else{
                $sale->payment_status = 'Paid';
            }
            $sale->sale_date = date('Y-m-d',strtotime($request->pay_date));
            $sale->sale_type = $request->sale_type;
            $sale->payment = $sale->payment + $request->payment;
            $sale->due_amount = $request->due_amount - $sale->payment;
            $sale->updated_by = Auth::id();
            $sale->note = $request->note;
            $sale->updated_by = Auth::id();
            $sale->save();

            if($request->payment > 0){
                $ca = new CustomerAccount();
                $ca->payment_date = date('Y-m-d',strtotime($request->pay_date));
                $ca->customer_id = $sale->customer_id;
                $ca->sale_id = $sale->id;
                $ca->amount = $request->payment;
                $ca->note = $request->note;
                $ca->save();
            }
            /*-------customer record section----------*/
            $cus = Customer::with('sales')->find($sale->customer_id);

            $record = new CustomerRecord();
            $record->customer_id = $sale->customer_id;
            $record->transaction_date = date('Y-m-d',strtotime($request->pay_date));
            $record->user_id = Auth::id();
            //$record->total_price = $request->grand_total;
            $record->payment_amount = $request->payment;
            $record->due_amount = $request->due_amount;
            $total_due = $cus->sales->sum('due_amount');
            $record->previous_due = $total_due - $request->due_amount;
            $record->total_due = $total_due;
            $record->note = $request->note;
            $record->message = "Dear Customer ".$cus->name.", your invoice total price is ".$request->grand_total."/=, Payment ".$request->payment."/= Due ".$request->due_amount."/= Previous Due ".$record->previous_due."/= Current Due ".$total_due." Thanks By ".about()->english_name.", ".about()->address;
            $record->created_by = Auth::id();
            $record->save();

            /*--------check the sms sending section--------*/
            if(isset($request->sms)){
                //return $request->sms;
                $to = $cus->phone;//"017xxxxxxx,+88016xxxxxxx";
                $token = "daf0cc0b638862523830815f351a8063";
                $message = "Dear customer invoice total:".$record->total_price.',pay:'.$record->payment_amount.',due:'.$record->due_amount.',prev due:'.$record->previous_due.',total due:'.$record->total_due.',Note:'.$record->note.',Date:'.date('d-m-Y',strtotime($record->transaction_date)).'.'.about()->english_name.','.about()->phone;
                $url = "http://api.greenweb.com.bd/api.php?json";
                $data= array(
                    'to'=>"$to",
                    'message'=>"$message",
                    'token'=>"$token"
                ); // Add parameters in key value

                $ch = curl_init(); // Initialize cURL
                curl_setopt($ch, CURLOPT_URL,$url);
                curl_setopt($ch, CURLOPT_ENCODING, '');
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $smsresult = curl_exec($ch);
                //Result
                //echo $smsresult;
                //Error Display
                //echo curl_error($ch);
            }
        }else{
            $sale->sale_type = $request->sale_type;
            $sale->cancel_date = date('Y-m-d',strtotime($request->pay_date));
            $sale->save();

            foreach($sale->details as $details){
                $product = Product::find($details->product_id);
                $stock = ProductionStock::where('product_id',$details->product_id)->first();
                if($stock != ''){
                    $stock->now_stock = $stock->now_stock + $details->quantity;
                    $stock->save();
                }
            }
        }
        
        return redirect()->route('sales.condition_list')->with('success','Sales Information update success');
    }
}
