<?php

namespace App\Http\Controllers\Dashboard;

use Exception;
use App\Models\Product;
use App\Models\Category;
use App\Models\Supplier;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Illuminate\Support\Facades\Redirect;

use PhpOffice\PhpSpreadsheet\Writer\Xls;
use Picqer\Barcode\BarcodeGeneratorHTML;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Haruncpi\LaravelIdGenerator\IdGenerator;

use App\Models\Tax;
use App\Models\Unit;
use App\Models\producttax;
use App\Models\stocklevel;

use App\Models\maincategory;

use DB;


class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
/*
        $row = (int) request('row', 10);

        if ($row < 1 || $row > 100) {
            abort(400, 'The per-page parameter must be an integer between 1 and 100.');
        }

        return view('products.index', [
            'products' => Product::with(['category', 'supplier'])
                ->filter(request(['search']))
                ->sortable()
                ->paginate($row)
                ->appends(request()->query()),
        ]);
   */
        $Products = Product::SELECT('products.product_code',
                                    'products.product_name',
                                    'products.category_id',
                                    'products.supplier_id',
                                    'products.BuyingUnit',
                                    'products.SellingUnit',
                                    'products.factor',
                                    'products.buying_price',
                                    'products.selling_price',
                                    'products.barcode',
                                    'products.tax_id',
                                    'products.SalesStatus',
                                    'products.Cauntable',
                                    'products.option1',
                                    'categories.name as category_name',
                                    'suppliers.name as suppliers_name'
                                    )
                           ->join('categories','categories.id','products.category_id')
                           ->join('suppliers','products.supplier_id','suppliers.id')
                           ->paginate(5);
        return view('products.index')->with('products',$Products);

    }


    public function productByCategory(Int $SubcategoryId){
       $Products = Product::SELECT('products.id',
                                    'products.product_code',
                                    'products.product_name',
                                    'products.category_id',
                                    'products.supplier_id',
                                    'products.BuyingUnit',
                                    'products.SellingUnit',
                                    'products.factor',
                                    'products.buying_price',
                                    'products.selling_price',
                                    'products.barcode',
                                    'products.tax_id',
                                    'products.SalesStatus',
                                    'products.Cauntable',
                                    'products.option1',
                                    'categories.name as category_name',
                                    'suppliers.name as suppliers_name'
                                    )
                           ->join('categories','categories.id','products.category_id')
                           ->join('suppliers','products.supplier_id','suppliers.id')
                           ->WHERE('category_id',$SubcategoryId)
                           ->paginate(5);
        return view('products.index',compact('SubcategoryId'))->with('products',$Products);
    }



    public function addProduct(Int $SubcategoryId){


        return view('products.create', [
            'categories' => Category::all(),
            'suppliers' => Supplier::all(),
            'taxes'=>Tax::all(),
            'units'=>Unit::all(),
            'SubcategoryId'=>$SubcategoryId
        ]);
    }






    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('products.create', [
            'categories' => Category::all(),
            'suppliers' => Supplier::all(),
            'taxes'=>Tax::all(),
            'units'=>Unit::all(),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
       // dd($request);
/*
        $product_code = IdGenerator::generate([
            'table' => 'products',
            'field' => 'product_code',
            'length' => 4,
            'prefix' => 'PC'
        ]);

        $rules = [
            'product_image' => 'image|file|max:1024',
            'product_name' => 'required|string',
            'category_id' => 'required|integer',
            'supplier_id' => 'required|integer',
            'tax_id' => 'required|integer',
            'product_garage' => 'string|nullable',
            'product_store' => 'string|nullable',
            'buying_date' => 'date_format:Y-m-d|max:10|nullable',
            'expire_date' => 'date_format:Y-m-d|max:10|nullable',
            'buying_price' => 'required|integer',
            'selling_price' => 'required|integer',
        ];


'product_code','product_name','category_id','supplier_id','BuyingUnit','SellingUnit',
            'factor','buying_price','selling_price','barcode','tax_id',
            'SalesStatus','Cauntable','option1','product_image'
*/

        $Product =  new Product();
        $Product->product_name = $request->product_name;
        $Product->product_code = $request->product_name;
        $Product->category_id = $request->category_id;
        $Product->supplier_id = $request->supplier_id;
        $Product->BuyingUnit = $request->BuyingUnit;
        $Product->SellingUnit = $request->SellingUnit;
        $Product->factor = $request->factor;
        $Product->buying_price = $request->buying_price;
        $Product->selling_price = $request->selling_price;
        $Product->barcode = $request->barcode;
        $Product->tax_id = $request->tax_id;
        $Product->SalesStatus = $request->SalesStatus;
        $Product->Cauntable = $request->Cauntable;
        $Product->option1 = $request->option1;


        $Product->save();








       /////// $validatedData = $request->validate($rules);



        // save product code value
       /////// $validatedData['product_code'] = $product_code;

        /**
         * Handle upload image with Storage.
         */
        if ($file = $request->file('product_image')) {
            $fileName = hexdec(uniqid()).'.'.$file->getClientOriginalExtension();
            $path = 'public/products/';

            $file->storeAs($path, $fileName);
            $validatedData['product_image'] = $fileName;
        }


        //$product = Product::create($validatedData);

        $stocklevel =  new stocklevel();
        $stocklevel->ItemCtrlNum = $Product->id;
        $stocklevel->Quantity = 0;

        $stocklevel->save();


        return Redirect::route('product.bycategory.list',$request->category_id)->with('success', 'Product has been created!');
    }

    /**
     * Display the specified resource.
     */
    public function show(Product $product)
    {
        // Barcode Generator
        $generator = new BarcodeGeneratorHTML();

        $barcode = $generator->getBarcode($product->product_code, $generator::TYPE_CODE_128);

        return view('products.show', [
            'product' => $product,
            'barcode' => $barcode,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Product $product)
    {
        return view('products.edit', [
            'categories' => Category::all(),
            'suppliers' => Supplier::all(),
            'product' => $product
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Product $product)
    {
        $rules = [
            'product_image' => 'image|file|max:1024',
            'product_name' => 'required|string',
            'category_id' => 'required|integer',
            'supplier_id' => 'required|integer',
            'product_garage' => 'string|nullable',
            'product_store' => 'string|nullable',
            'buying_date' => 'date_format:Y-m-d|max:10|nullable',
            'expire_date' => 'date_format:Y-m-d|max:10|nullable',
            'buying_price' => 'required|integer',
            'selling_price' => 'required|integer',
        ];

        $validatedData = $request->validate($rules);

        /**
         * Handle upload image with Storage.
         */
        if ($file = $request->file('product_image')) {
            $fileName = hexdec(uniqid()).'.'.$file->getClientOriginalExtension();
            $path = 'public/products/';

            /**
             * Delete photo if exists.
             */
            if($product->product_image){
                Storage::delete($path . $product->product_image);
            }

            $file->storeAs($path, $fileName);
            $validatedData['product_image'] = $fileName;
        }

        Product::where('id', $product->id)->update($validatedData);

        return Redirect::route('products.index')->with('success', 'Product has been updated!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Product $product)
    {
        /**
         * Delete photo if exists.
         */
        if($product->product_image){
            Storage::delete('public/products/' . $product->product_image);
        }

        Product::destroy($product->id);

        return Redirect::route('products.index')->with('success', 'Product has been deleted!');
    }

    /**
     * Show the form for importing a new resource.
     */
    public function importView()
    {
        return view('products.import');
    }

    public function importStore(Request $request)
    {
        $request->validate([
            'upload_file' => 'required|file|mimes:xls,xlsx',
        ]);

        $the_file = $request->file('upload_file');

        try{
            $spreadsheet = IOFactory::load($the_file->getRealPath());
            $sheet        = $spreadsheet->getActiveSheet();
            $row_limit    = $sheet->getHighestDataRow();
            $column_limit = $sheet->getHighestDataColumn();
            $row_range    = range( 2, $row_limit );
            $column_range = range( 'J', $column_limit );
            $startcount = 2;
            $data = array();
            foreach ( $row_range as $row ) {
                $data[] = [
                    'product_name' => $sheet->getCell( 'A' . $row )->getValue(),
                    'category_id' => $sheet->getCell( 'B' . $row )->getValue(),
                    'supplier_id' => $sheet->getCell( 'C' . $row )->getValue(),
                    'product_code' => $sheet->getCell( 'D' . $row )->getValue(),
                    'product_garage' => $sheet->getCell( 'E' . $row )->getValue(),
                    'product_image' => $sheet->getCell( 'F' . $row )->getValue(),
                    'product_store' =>$sheet->getCell( 'G' . $row )->getValue(),
                    'buying_date' =>$sheet->getCell( 'H' . $row )->getValue(),
                    'expire_date' =>$sheet->getCell( 'I' . $row )->getValue(),
                    'buying_price' =>$sheet->getCell( 'J' . $row )->getValue(),
                    'selling_price' =>$sheet->getCell( 'K' . $row )->getValue(),
                ];
                $startcount++;
            }

            Product::insert($data);

        } catch (Exception $e) {
            // $error_code = $e->errorInfo[1];
            return Redirect::route('products.index')->with('error', 'There was a problem uploading the data!');
        }
        return Redirect::route('products.index')->with('success', 'Data has been successfully imported!');
    }

    public function exportExcel($products){
        ini_set('max_execution_time', 0);
        ini_set('memory_limit', '4000M');

        try {
            $spreadSheet = new Spreadsheet();
            $spreadSheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
            $spreadSheet->getActiveSheet()->fromArray($products);
            $Excel_writer = new Xls($spreadSheet);
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="Products_ExportedData.xls"');
            header('Cache-Control: max-age=0');
            ob_end_clean();
            $Excel_writer->save('php://output');
            exit();
        } catch (Exception $e) {
            return;
        }
    }

    /**
     *This function loads the customer data from the database then converts it
     * into an Array that will be exported to Excel
     */
    function exportData(){
        $products = Product::all()->sortByDesc('product_id');

        $product_array [] = array(
            'Product Name',
            'Category Id',
            'Supplier Id',
            'Product Code',
            'Product Garage',
            'Product Image',
            'Product Store',
            'Buying Date',
            'Expire Date',
            'Buying Price',
            'Selling Price',
        );

        foreach($products as $product)
        {
            $product_array[] = array(
                'Product Name' => $product->product_name,
                'Category Id' => $product->category_id,
                'Supplier Id' => $product->supplier_id,
                'Product Code' => $product->product_code,
                'Product Garage' => $product->product_garage,
                'Product Image' => $product->product_image,
                'Product Store' =>$product->product_store,
                'Buying Date' =>$product->buying_date,
                'Expire Date' =>$product->expire_date,
                'Buying Price' =>$product->buying_price,
                'Selling Price' =>$product->selling_price,
            );
        }

        $this->ExportExcel($product_array);
    }

    public function defaultTax(Int $ItemId,Int $TaxId){
        $producttax = new producttax();
        $producttax->ProductId = $ItemId;
        $producttax->TaxId = $TaxId;
        $producttax->save();
    }


   public function Categories(){

        $row = (int) request('row', 10);

        if ($row < 1 || $row > 100) {
            abort(400, 'The per-page parameter must be an integer between 1 and 100.');
        }

        return view('products.category', [
            'categories' => maincategory::filter(request(['search']))
                ->sortable()
                ->paginate($row)
                ->appends(request()->query()),
        ]);
    }



    public function subCategories(){
       dd('test');
    }
    public function ItemList(){
       dd('test');
    }

    public function barcode(Int $productId){
        $Product = Product::findorfail($productId);
        dd($Product->barcode);
    }


    public function viewProduct($ProductId,$SubcategoryId){


        return view('products.editView', [
            'product' => Product::findorfail($ProductId),
            'categories' => Category::all(),
            'suppliers' => Supplier::all(),
            'taxes'=>Tax::all(),
            'units'=>Unit::all(),
            'SubcategoryId'=>$SubcategoryId
        ]);

    }

    public function product_update(Request $request, Int $id){


        $product = Product::find($id);

        $CategoryId = $product->category_id ;

        $product->product_code = $request->product_name;
        $product->product_name = $request->product_name;
        $product->category_id = $request->category_id;
        $product->supplier_id = $request->supplier_id;
        $product->BuyingUnit = $request->BuyingUnit;
        $product->SellingUnit = $request->SellingUnit;
        $product->factor = $request->factor;
        $product->buying_price = $request->buying_price;
        $product->selling_price = $request->selling_price;
        $product->barcode = $request->barcode;
        $product->tax_id = $request->tax_id;
        $product->SalesStatus = $request->SalesStatus;
        $product->Cauntable = $request->Cauntable;
        $product->option1 = $request->option1;


        $product->update();

        return redirect()->route('product.bycategory.list',$CategoryId);

    }
    
    
    
    public function product_search(Request $request){
        $query = "SELECT a.id, a.product_code, a.product_name, a.category_id, a.supplier_id, a.BuyingUnit, a.SellingUnit, 
                        a.factor, a.buying_price, a.selling_price, a.barcode, 
                        a.tax_id, a.SalesStatus, a.Cauntable, a.option1, a.product_image,b.name category_name,c.name suppliers_name
                  FROM  products a,categories b,suppliers c 
                  WHERE product_code like '%".$request->search."%' and a.category_id = b.id and a.supplier_id = c.id";
        
       
        $Products =DB::SELECT($query);
        
        return view('products.search')->with('products',$Products);
        //dd($products);
        /*
        foreach($products as $product){
            echo "test";
        }
        */
        
    }


}
