<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Models\Unit;
use App\Models\Productcategory;
use App\Models\Product;
use App\Models\Purchase;
use App\Models\Supplier;
use App\Models\Customer;
use App\Models\CustomerAccount;
use App\Models\Sale;
use App\Models\SaleDetail;
use App\Models\PurchaseDetail;
use DB;

class PosController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $invoice = Sale::where('sale_date',date('Y-m-d'))->latest()->first();
        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';
        }
        return view('backend.pos.create',compact('inv_no'));
    }
    // public function productList3(Request $request){
    //     $products  = DB::table('purchase_stocks')
    //                     ->join('products', 'purchase_stocks.product_id', '=', 'products.id')
    //                     ->select('purchase_stocks.*','products.product_name','products.code')
    //                     ->where('purchase_stocks.productcategory_id',$request->type)
    //                     ->get(); 
    //     return response()->json($products);
    // }
    public function productDetails3(Request $request){
           //$products = PurchaseDetail::find($request->id);
           $products  = DB::table('purchase_stocks')
                        ->join('products', 'purchase_stocks.product_id', '=', 'products.id')
                        ->join('productcategories', 'purchase_stocks.productcategory_id', '=', 'productcategories.id')
                        ->join('units', 'purchase_stocks.unit_id', '=', 'units.id')
                        ->select('purchase_stocks.*','products.product_name','products.size','products.sale_price', 'products.code','productcategories.name as category_name','units.name as unit_name')
                        ->where('purchase_stocks.code',$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');
            $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';
            }
            
            $dt = Carbon::parse($request->sale_date);
            $date = $dt->toDateTimeString();
            $sale = new Sale();
            $sale->user_id = Auth::id();
            $dt = Carbon::parse($request->sale_date);
            $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->total_price = $request->total_price;
            $sale->discount = $request->discount;
        // $sale->shiping_cost = $request->shiping_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->save();

            $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['product_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['size'][$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*/
                //DB::table('purchase_details')->where('id', '=', $data['purchase_details_id'][$i])->decrement('now_stock', $data['tsqf'][$i]);
                DB::table('purchase_stocks')->where('product_id', '=', $data['product_id'][$i])->decrement('now_stock', $data['ordered_quantity'][$i]);

            };

   

         return back()->with('success','Sales Information Save Successfull');
         
        }
        else{
            return redirect()->back()->with('error','Woops! After cash closing all transaction has been stoped');
        }
    }
    /*------barcode generate section */
    public function index(){
        $stocks  = DB::table('purchase_stocks')
                        ->join('products', 'purchase_stocks.product_id', '=', 'products.id')
                        ->join('productcategories', 'purchase_stocks.productcategory_id', '=', 'productcategories.id')
                        ->join('units', 'purchase_stocks.unit_id', '=', 'units.id')
                        ->select('purchase_stocks.*','purchase_stocks.now_stock as product_stock','products.product_name as product_name','products.code','products.re_order_label', 'productcategories.name as category_name','units.name as unit_name')
                        ->get();
        $products = Product::where('status',1)->get();
       return view('backend.pos.index',compact('stocks','products'));
    }
    public function barcode_generate(Request $request, $id){
        $product = PurchaseDetail::find($id);
        return view('backend.pos.barcode_generate',compact('product'));
    }
    public function qrcode_generate(Request $request, $id){
        $product = PurchaseDetail::find($id);
        return view('backend.pos.qrcode_generate',compact('product'));
    }
}
