<?php

namespace Modules\Admin\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Facades\Excel;

use App\Models\User;
use App\Models\AdminDetails;
use App\Models\Companies;
use App\Models\Supliers;
use App\Models\Categories;
use App\Models\Brands;
use App\Models\Products;
use App\Models\ProductGallery;
use App\Models\Banners;

use File;
use Mail;
use Image;
use PDF;
class ProductController extends Controller
{
    public function add_company(Request $request)
    { if($request->isMethod('get')){
        return view('admin::product.add_company');
    }
    if($request->isMethod('post')){

 $request->validate([
            'company_name' => 'required|unique:companies',
        ]);
        $company = new Companies();
        $company->company_name =$request->company_name;
        $company->address = $request->address;
        $company->contact_person = $request->contact_person;
        $company->email = $request->email;
        $company->phone_number = $request->phone_number;
        $company->company_website = $request->company_website;
        $company->payment_terms = $request->payment_terms;
        $company->status = "active";
        $company->save();

        return back()->with('success', 'Company Successfully Added');

    }

    }
    public function companies()
    {
        $companies = Companies::get();
        return view('admin::product.companies',['companies' => $companies]);
    }
    public function deactivate_company($id){
        $company = Companies::find($id);
        $company->status = "inactive";
        $company->update();
        return back()->with('success', 'Company Deactivated');

    }
    public function activate_company($id){
        $company = Companies::find($id);
        $company->status = "active";
        $company->update();
        return back()->with('success', 'Company Activated');

    }
    public function edit_company($id,Request $request)
    {
    if($request->isMethod('get')){
    $company_details = Companies::where('id',$id)->first();
    return view('admin::product.edit_company', ['company_details' => $company_details]);
    }
    if($request->isMethod('post')){

if(Companies::where("id", $id)->where("company_name", $request->company_name)->exists()){
            $company_name = $request->company_name;
        }
        elseif(Companies::where("company_name", $request->company_name)->exists()){
         return back()->with('fail', 'This company name is already in use');
        }
        else{
         $company_name = $request->company_name;
        }
        $company = Companies::find($id);
        $company->company_name =$company_name;
        $company->address = $request->address;
        $company->contact_person = $request->contact_person;
        $company->email = $request->email;
        $company->phone_number = $request->phone_number;
        $company->company_website = $request->company_website;
        $company->payment_terms = $request->payment_terms;
        $company->update();

        return back()->with('success', 'Company Details Successfully  Updated');
    }

    }
    public function delete_company($id){
        Companies::find($id)->delete();
        return back()->with('success', 'Company Deleted');

    }
    public function add_suplier(Request $request)
    { if($request->isMethod('get')){
        $companies = Companies::where('status','active')->get();
        return view('admin::product.add_suplier',['companies' => $companies]);
    }
    if($request->isMethod('post')){

$request->validate([
            'suplier_id' => 'required|unique:supliers',
        ]);
        
        $suplier = new Supliers();
        $suplier->suplier_name =$request->suplier_name;
        $suplier->suplier_id = $request->suplier_id;
        $suplier->contact_details = $request->contact_details;
        $suplier->associated_company = $request->associated_company;
        $suplier->email = $request->email;
        $suplier->phone_number = $request->phone_number;
        $suplier->status = "active";
        $suplier->save();

        return back()->with('success', 'Suplier Successfully Added');

    }

    }
    public function supliers()
    {
        $supliers = Supliers::get();
        return view('admin::product.supliers',['supliers' => $supliers]);
    }
    public function deactivate_suplier($id){
        $suplier = Supliers::find($id);
        $suplier->status = "inactive";
        $suplier->update();
        return back()->with('success', 'Suplier Deactivated');

    }
    public function activate_suplier($id){
        $suplier = Supliers::find($id);
        $suplier->status = "active";
        $suplier->update();
        return back()->with('success', 'Suplier Activated');

    }
    public function delete_suplier($id){
        Supliers::find($id)->delete();
        return back()->with('success', 'Suplier Deleted');

    }
    public function edit_suplier($id,Request $request)
    {
    if($request->isMethod('get')){
    $suplier_details = Supliers::where('id',$id)->first();
    $companies = Companies::where('status','active')->get();
    return view('admin::product.edit_suplier', ['suplier_details' => $suplier_details,'companies' => $companies]);
    }
    if($request->isMethod('post')){

 if(Supliers::where("id", $id)->where("suplier_id", $request->suplier_id)->exists()){
            $suplier_id = $request->suplier_id;
        }
        elseif(Supliers::where("suplier_id", $request->suplier_id)->exists()){
         return back()->with('fail', 'This suplier id is already in use');
        }
        else{
         $suplier_id = $request->suplier_id;
        }
        
        $suplier = Supliers::find($id);
        $suplier->suplier_name =$request->suplier_name;
        $suplier->suplier_id = $suplier_id;
        $suplier->contact_details = $request->contact_details;
        $suplier->associated_company = $request->associated_company;
        $suplier->email = $request->email;
        $suplier->phone_number = $request->phone_number;
        $suplier->update();

        return back()->with('success', 'Suplier Details Successfully  Updated');
    }

    }
    public function categories(Request $request)
    { if($request->isMethod('get')){
        $categories = Categories::get();
        $parent_categories = Categories::where('status','active')->where('parent_category', 'none')->get();
        return view('admin::product.categories',['parent_categories' => $parent_categories
        ,'categories' => $categories]);
    }
    if($request->isMethod('post')){

        $category = new Categories();
        $category->parent_category =$request->parent_category;
        $category->category_name =$request->category_name;
        $category->status = "active";
        $category->save();

        return back()->with('success', 'Categories Successfully Added');

    }

    }
    public function deactivate_category($id){
        $category = Categories::find($id);
        $category->status = "inactive";
        $category->update();
        return back()->with('success', 'Category Deactivated');

    }
    public function activate_category($id){
        $category = Categories::find($id);
        $category->status = "active";
        $category->update();
        return back()->with('success', 'Category Activated');

    }
    public function edit_category($id,Request $request)
    {
    if($request->isMethod('get')){
    $category_details = Categories::where('id',$id)->first();
    $parent_categories = Categories::where('status','active')->where('parent_category', 'none')->get();
    return view('admin::product.edit_category', ['category_details' => $category_details,'parent_categories' => $parent_categories]);
    }
    if($request->isMethod('post')){

        $category = Categories::find($id);
        $category->parent_category =$request->parent_category;
        $category->category_name =$request->category_name;
        $category->update();

        return back()->with('success', 'Category Details Successfully  Updated');
    }

    }
    public function delete_category($id){
        Categories::find($id)->delete();
        return back()->with('success', 'Category Deleted');

    }
    public function brands(Request $request)
    { if($request->isMethod('get')){
        $brands = Brands::get();
        return view('admin::product.brands',['brands' => $brands]);
    }
    if($request->isMethod('post')){

        $brand = new Brands();
        $brand->brand_name =$request->brand_name;
        $brand->status = "active";
        $brand->save();

        return back()->with('success', 'Brand Successfully Added');

    }

    }
    public function deactivate_brand($id){
        $brand = Brands::find($id);
        $brand->status = "inactive";
        $brand->update();
        return back()->with('success', 'Brand Deactivated');

    }
    public function activate_brand($id){
        $brand = Brands::find($id);
        $brand->status = "active";
        $brand->update();
        return back()->with('success', 'Brand Activated');

    }
    public function delete_brand($id){
        Brands::find($id)->delete();
        return back()->with('success', 'Brand Deleted');

    }
    public function edit_brand($id,Request $request)
    {
    if($request->isMethod('get')){
    $brand_details = Brands::where('id',$id)->first();
    return view('admin::product.edit_brand', ['brand_details' => $brand_details]);
    }
    if($request->isMethod('post')){

        $brand = Brands::find($id);
        $brand->brand_name =$request->brand_name;
        $brand->update();

        return back()->with('success', 'Brand Details Successfully  Updated');
    }

    }
    public function banners(Request $request)
    { if($request->isMethod('get')){
        $banners = Banners::get();
        return view('admin::product.banners',['banners' => $banners]);
    }
    if($request->isMethod('post')){

        $request->validate([
            'url'   => 'required',
            'order'   => 'required',
            'image'   => 'required',
        ]);

        $image = time().'-featured-.'.$request->image->extension();
        $request->image->move(public_path('db_files/banners'), $image);
        $image_url = asset('db_files/banners/').'/'.$image;
        
        
        $banner = new Banners();
        $banner->url =$request->url;
        $banner->order =$request->order;
        $banner->image =$image;
        $banner->image_url =$image_url;
        $banner->status = "active";
        $banner->save();

        return back()->with('success', 'Banner Successfully Added');

    }

    }
    public function deactivate_banner($id){
        $banner = Banners::find($id);
        $banner->status = "inactive";
        $banner->update();
        return back()->with('success', 'Banner Deactivated');

    }
    public function activate_banner($id){
        $banner = Banners::find($id);
        $banner->status = "active";
        $banner->update();
        return back()->with('success', 'Banner Activated');

    }
    public function delete_banner($id){
        Banners::find($id)->delete();
        return back()->with('success', 'Banner Deleted');

    }
    public function edit_banner($id,Request $request)
    {
    if($request->isMethod('get')){
    $banner_details = Banners::where('id',$id)->first();
    return view('admin::product.edit_banner', ['banner_details' => $banner_details]);
    }
    if($request->isMethod('post')){

        if($request->featured_image == null){
            $image =  Banners::where('id', $id)->value('image');
            $image_url =  asset('db_files/banners/').'/'.$image;
        }
        else{
            $image = time().'-featured-.'.$request->image->extension();
            $request->image->move(public_path('db_files/banners'), $image);
            $image_url = asset('db_files/banners/').'/'.$image;
        }

        $banner = Banners::find($id);
        $banner->url =$request->url;
        $banner->order =$request->order;
        $banner->image =$image;
        $banner->image_url =$image_url;
        $banner->update();

        return back()->with('success', 'Banner Details Successfully  Updated');
    }

    }
    public function select_web_categories(Request $request)
    { if($request->isMethod('get')){
        $categories = Categories::where('status','active')->get();
        return view('admin::product.select_web_categories',['categories' => $categories]);
    }
    if($request->isMethod('post')){

        if($request->check_category){
        foreach ($request->check_category as $category) {
        $category = Categories::find($category);
        $category->is_web = "yes";
        $category->update();
        }
        }

        return back()->with('success', 'Categories Updated');

    }

    }
    public function add_product(Request $request)
    {
        if($request->isMethod('get')){
            $parent_categories = Categories::where('status','active')->where('parent_category', 'none')->get();
            $supliers = Supliers::where('status','active')->get();
            $brands = Brands::where('status','active')->get();
            return view('admin::product.add_product',[
                'parent_categories' => $parent_categories,
                'supliers' => $supliers,
                'brands' => $brands
            ]);
        }

        if($request->isMethod('post')){
            $request->validate([
                'product_name'   => 'required',
                'product_code'   => 'required',
                // 'parent_category'   => 'required',
                // 'sub_category'   => 'required',
                // 'suplier'   => 'required',
                // 'brand'   => 'required',
            ]);

            if($request->featured_image == null){
                $featured_image =  "-";
                $featured_image_url =  "-";
            } else {
                $featured_image = time().'-featured-.'.$request->featured_image->extension();
                $request->featured_image->move(public_path('db_files/product_images'), $featured_image);
                $featured_image_url = asset('db_files/product_images/').'/'.$featured_image;
            }

            $product = new Products();
            $product->product_name = $request->product_name;
            $product->product_code = $request->product_code;
            $product->parent_category = $request->parent_category;
            $product->sub_category = $request->sub_category;
            $product->suplier = $request->suplier;
            $product->brand = $request->brand;
            $product->sku = $request->sku;
            $product->barcode = $request->barcode;
            $product->warehouse_location = $request->warehouse_location;
            $product->units = $request->units;
            $product->carton_size = $request->carton_size;
            $product->description = $request->description;
            $product->stock_alert_quantity = $request->stock_alert_quantity;
            $product->featured_image = $featured_image;
            $product->featured_image_url = $featured_image_url;
            $product->status = "active";
            $product->save();

            if($request->hasFile("gallery_images")){
                $file_array = $request->file("gallery_images");
                foreach($file_array as $file){
                    $file_name = time().'-gallery-'.$file->getClientOriginalName();
                    $file->move(public_path('db_files/product_images'), $file_name);
                    $image_url = asset('db_files/product_images/').'/'.$file_name;
                    $product_gallery = new ProductGallery();
                    $product_gallery->product_id = $product->id;
                    $product_gallery->image = $file_name;
                    $product_gallery->image_url = $image_url;
                    $product_gallery->save();
                }
            }

            return back()->with('success', 'Product Successfully Added');
        }
    }

    
public function get_sub_categories($parentId)
{
    $subcategories = Categories::where('parent_category', $parentId)->get();
    return response()->json($subcategories);
}
public function products(Request $request)
    { if($request->isMethod('get')){
        $products = Products::where('status', 'active')->orWhere('status', 'inactive')->get();
        return view('admin::product.products',['products' => $products]);
    }

    }
    public function product_overview(Request $request)
    { if($request->isMethod('get')){
        $products = Products::where('status', 'active')->orWhere('status', 'inactive')->get();
        return view('admin::product.product_overview',['products' => $products]);
    }

    }
    public function deactivate_product($id){
        $product = Products::find($id);
        $product->status = "inactive";
        $product->update();
        return back()->with('success', 'Product Deactivated');

    }
    public function activate_product($id){
        $product = Products::find($id);
        $product->status = "active";
        $product->update();
        return back()->with('success', 'Product Activated');

    }

    public function edit_product($id,Request $request)
    { if($request->isMethod('get')){
        $parent_categories = Categories::where('status','active')->where('parent_category', 'none')->get();
        $supliers = Supliers::where('status','active')->get();
        $brands = Brands::where('status','active')->get();
        $product_details = Products::where('id',$id)->first();
        $product_gallery = ProductGallery::where('product_id',$id)->get();
        return view('admin::product.edit_product',['parent_categories' => $parent_categories,'supliers' => $supliers,'brands' => $brands
        ,'product_details' => $product_details,'product_gallery' => $product_gallery]);
    }
    if($request->isMethod('post')){
        $request->validate([
            'product_name'   => 'required',
            'product_code'   => 'required',
            // 'parent_category'   => 'required',
            // 'sub_category'   => 'required',
            // 'suplier'   => 'required',
            // 'brand'   => 'required',
        ]);

        if($request->featured_image == null){
            $featured_image =  Products::where('id', $id)->value('featured_image');
            $featured_image_url =  asset('db_files/product_images/').'/'.$featured_image;
        }
        else{
            $featured_image = time().'-featured-.'.$request->featured_image->extension();
            $request->featured_image->move(public_path('db_files/product_images'), $featured_image);
             $featured_image_url =  asset('db_files/product_images/').'/'.$featured_image;
        }

        $product = Products::where('id', $id)->first();
        $product->product_name =$request->product_name;
        $product->product_code = $request->product_code;
        $product->parent_category = $request->parent_category;
        $product->sub_category = $request->sub_category;
        $product->suplier = $request->suplier;
        $product->brand = $request->brand;
        // $product->wholesale_purchase_price = $request->wholesale_purchase_price;
        // $product->wholesale_selling_price = $request->wholesale_selling_price;
        // $product->retail_purchase_price = $request->retail_purchase_price;
        // $product->retail_selling_price = $request->retail_selling_price;
        $product->sku = $request->sku;
        $product->barcode = $request->barcode;
        // $product->min_stock = $request->min_stock;
        // $product->max_stock = $request->max_stock;
        $product->warehouse_location = $request->warehouse_location;
        $product->units = $request->units;
        $product->carton_size = $request->carton_size;
        $product->description = $request->description;
        $product->featured_image = $featured_image;
        $product->featured_image_url = $featured_image_url;
        $product->stock_alert_quantity = $request->stock_alert_quantity;
        $product->update();

        if($request->hasFile("gallery_images"))
            {
             $file_array = $request->file("gallery_images");
             $array_len = count($file_array);
             for($i = 0; $i<$array_len; $i++){
                 $file_name = time().'-gallery-'.$file_array[$i]->getClientOriginalName();
                 $save_path = public_path('db_files/product_images');
                 $file_array[$i]->move($save_path, $file_name);
                 $image_url = asset('db_files/product_images/').'/'.$file_name;
                 $product_gallery = new ProductGallery();
                 $product_gallery->product_id =$product->id;
                 $product_gallery->image = $file_name;
                 $product_gallery->image_url = $image_url;
                 $product_gallery->save();
             }
        }

        return back()->with('success', 'Product Successfully Added');

    }

    }

    public function delete_product($id,Request $request)
    {
        Products::find($id)->delete();
        ProductGallery::where('product_id', '=', $id)->delete();;
        return back()->with('success', 'Product Deleted');
    }
    public function delete_gallery_image($id,Request $request)
    {
        ProductGallery::where('id', $id)->delete();
        return back()->with('success', 'Image Successfully Deleted');
    }
public function import_products(Request $request){ 
    
    if($request->isMethod('get')){
        $products = Products::where('status', 'draft')->get();
        return view('admin::product.import_products',['products' => $products]);
    }
    if($request->isMethod('post')){

    $request->validate([
        'import' => 'required|mimes:xlsx,csv,txt|max:10240',
    ]);
      
      
    $file = $request->file('import');
    $data = Excel::toArray([], $file);
    $rows = $data[0];
    $header = array_shift($rows);
    
    foreach ($rows as $row) {

            $record = array_combine($header, $row);
            $parent_category = Categories::withTrashed()->where('slug', $record['parent_category'])->value('id');
            $sub_category = Categories::withTrashed()->where('slug', $record['sub_category'])->value('id');
            $suplier = Supliers::withTrashed()->where('slug', $record['suplier'])->value('id');
            $brand = Brands::withTrashed()->where('slug', $record['brand'])->value('id');
            
            Products::create([
                'product_name' => $record['product_name'] ?? '',
                'product_code' => $record['product_code'] ?? '',
                'parent_category' => $parent_category ?? '',
                'sub_category' => $sub_category ?? '',
                'suplier' => $suplier ?? '',
                'brand' => $brand ?? '',
                'sku' => $record['sku'] ?? '',
                'barcode' => $record['barcode'] ?? '',
                'warehouse_location' => $record['warehouse_location'] ?? '',
                'units' => $record['units'] ?? '',
                'carton_size' => $record['carton_size'] ?? '',
                'description' => $record['description'] ?? '',
                'status' => "draft",
            ]);
            

    }
    
    return back()->with('success', 'Products Successfully Imported');
        
    }

}
public function update_gallery_url()
{
    $product_gallery = ProductGallery::get();
    foreach($product_gallery as $product_gallery){
        $gallery = ProductGallery::where('id', $product_gallery->id)->first();
        $gallery->image_url = asset('db_files/product_images/').'/'.$product_gallery->image;
        $gallery->update();
    }
}
}