<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Models\Company;
use App\Models\Country;
use App\Models\State;
use App\Models\City;
use App\Models\User;
use App\Models\VisitorCompanyRelation;
use App\Exports\CompanyExport;
use App\Imports\CompanyImport;
use Maatwebsite\Excel\Facades\Excel;

class CompanyController extends Controller
{
    public function __construct()
	{	
		$this->middleware(function ($request, $next) 
        {
			// fetch session and use it in entire class with constructor
            if(session()->get('loggedIn')['user_type'] == 'admin')
			{
				$this->admin_id = session()->get('loggedIn')['id'];
			}
            else
            {
				$this->admin_id = session()->get('loggedIn')['admin_id'];
			}				
			    return $next($request);
		});

	}

    public function export()
    {
        // Export Data
        $filename = "company.xlsx";
        return Excel::download(new CompanyExport, $filename);
    }

    public function import(Request $request)
    {
       
        $file = $request->file('excel_file');
        

        Excel::import(new CompanyImport, $file);

        return response()->json(["message"=>"success"],200);
    }

    public function index()
    {
        
        $this->data["company"] = Company::with(['user','country','state','loc_country','loc_state'])->where('admin_id',\Auth::user()->id)->paginate(10);            
        $this->data["mainSuperAdminMenu"] = "company";
        $this->data["superadminSubMenu"] = "company-list";
        return view('company.company-list',$this->data);        
            
    }

    public function addCompany()
    {                    
        $this->data["mainSuperAdminMenu"] = "company";
        $this->data["superadminSubMenu"] = "company-list";
        $this->data["country"] = Country::get();
        return view('company.add-company',$this->data);
    }
    
   

    public function storeCompany(Request $request)
    {
        $this->allData = $request->all();
        
        //return $this->allData;
        $id = Auth::user()->id;
        $user = User::where('id',$id)->first();
        $branch = $user->branch_limit;

        //check limit of company
        $count = Company::where('admin_id',$this->admin_id)->count();
        
        if($count >= $branch)
        {
            return back()->with("error","Only 3 Organization Allowed Please Contact Superadmin or Owner");
        }

        $this->validator = Validator::make($this->allData, [
            'company_name' => "required",
            'email' => "required",           
            "phone" => "required|numeric",
            "gst_treatment"=> 'required',
            "gstn"=>"required",
            "location_type"=>"required"
           
        ]);
        
        if ($this->validator->fails()) 
        {
            return back()->withErrors($this->validator)->withInput();
        }
        else
        {
            $pattern="GA0a!b1|cBdN@efg2hCiH3`jkD#lP4OmM%n^JVoQ5pRE_<q=)SIK9rs6&tT*uUF,L-(vZ7w~Wx+8yX>zY";
            $length = strlen($pattern)-1;
            $i;
            $code =[];
            for($i=0;$i<8;$i++)
            {
                $indexing_number = rand(0,$length);
                $code[] = $pattern[$indexing_number];
            }
            $slug = implode($code);

            $this->allData["admin_id"] = $this->admin_id;
            $this->allData["slug"] = $slug;

            
            $this->res = Company::create($this->allData);

            if($this->res)
            {
                VisitorCompanyRelation::create([
                    "company_id" => $this->res->id,
                    "user_id" => $this->admin_id
                ]);
                return back()->with("success","Company created successfully !");
               
               
            }
            else
            {
               return back()->with("error","Failed !");
            }
        }
        
    }

    public function viewCompany($id)
    {
        $this->data["mainSuperAdminMenu"] = "company";
        $this->data["superadminSubMenu"] = "company-list";
        $this->data["company"] = Company::where('id',$id)->first();
        return view('company.view',$this->data);
    }

    public function editCompany($id)
    {
        $this->data["mainSuperAdminMenu"] = "company";
        $this->data["superadminSubMenu"] = "company-list";
       
        $this->data["company"] = Company::with(['country','state','loc_country','loc_state'])->where('id',$id)->first();
        $this->data["country"] = Country::get();
        return view('company.edit',$this->data); 
    }

    public function updateCompany(Request $request)
    {
        $this->allData = $request->all();

        //return $this->allData;

        $this->validator = Validator::make($this->allData, [
            'company_name' => "required",
            'email' => "required",           
            "phone" => "required|numeric",
            "gst_treatment"=> 'required',
            "gstn"=>"required",
            "location_type"=>"required"
        ]);
        
        if ($this->validator->fails()) 
        {
            return back()->withErrors($this->validator)->withInput();
        }
        else
        {
            unset($this->allData["company_id"]);
            unset($this->allData["_token"]);
            
            $this->res = Company::where("id",$request->company_id)->update($this->allData);

            if($this->res)
            {
                return back()->with("success","Company updated successfully !");
            }
            else
            {
               return back()->with("error","Failed !");
            }
        }
    }

    public function delete($id)
    {
        $this->res = Company::where('id',$id)->delete();

        if($this->res)
        {
            return back()->with('success',"Delete Successfully !");
        }
        else
        {
            return back()->with('error',"Failed !");
        }
    }

    public function filterCompany(Request $request)
    {
        $this->data["mainSuperAdminMenu"] = "company";
        $this->data["superadminSubMenu"] = "company-list";

        $query = Company::where("admin_id", "=", $this->admin_id);

        // Get search parameters from request
        $search = $request->input("search");
        $city = $request->input("city");
        $phone = $request->input("phone");
        $email = $request->input("email");
        $contact_name = $request->input("contact_name");
        $contact_email = $request->input("contact_email");

        // Apply search conditions based on provided inputs
        if ($search) {
            $query->where('company_name', 'LIKE', '%' . $search . '%');
        }
        if ($city) {
            $query->where('location_city', 'LIKE', '%' . $city . '%');
        }
        if ($phone) {
            $query->where('phone', 'LIKE', '%' . $phone . '%');
        }
        if ($email) {
            $query->where('email', 'LIKE', '%' . $email . '%');
        }
        if ($contact_name) {
            $query->where('contact_name', 'LIKE', '%' . $contact_name . '%');
        }
        if ($contact_email) {
            $query->where('contact_email', 'LIKE', '%' . $contact_email . '%');
        }

        // Execute the query and paginate the results
        $this->data["company"] = $query->orderBy('created_at', 'desc')->paginate(20);

        return view('company.company-list', $this->data);
    }

    public function searchCompany(Request $request)
    {
        
            $this->data["company"] = Company::where([
                ['admin_id', '=', $this->admin_id],
                ['company_name', 'LIKE', '%'.$request->search.'%']
            ])->get();

            return $this->data;
        
    }

    public function deleteMultiple(Request $request)
    {
        $count = 0;

        foreach($request->ids as $id)
        {
            Company::where('id',$id)->delete();   
            $count++;    
        }
        if($count)
        {
            return "success";
        }
        else
        {
            return "failed";
        }
    }

   //country related code
   public function fetachState(Request $request)
   {
       //return $request->all();
       $this->res = State::where('country_code',$request->id)->get();
       if($this->res->count())
       {
           return response()->json(["message"=>"success","data"=>$this->res],200);
       }
       else
       {
           return response()->json(["message"=>"failed"],404);
       }
   }

   public function searchCity(Request $request)
   {
       $this->res = City::where('city_name','LIKE','%'.$request->search.'%')->get();

       if($this->res->count())
       {
           return response()->json(["message"=>"success","data"=>$this->res]);
       }
       else
       {
           return response()->json(["message"=>"failed"],200);
       }
   }

   public function addCity(Request $request)
   {
       $this->allData = $request->all();
       //return $this->allData;

       $this->validator = Validator::make($this->allData, [
           'city_name' => "required"
       ]);
       
       if ($this->validator->fails()) 
       {
           return "failed";
       }
       else
       {
           $this->res = City::create(['city_name'=>$request->city_name]);

           if($this->res)
           {
               return response()->json(["message"=>"success","data"=>$this->res->city_name],200);
           }
           else
           {
               return response()->json(["message"=>"failed"],409);
           }
       }
   }

   public function fetchCity(Request $request)
    {
        $this->res = City::get();

        if($this->res->count())
        {
            return response()->json(["message"=>"success","data"=>$this->res]);
        }
        else
        {
            return response()->json(["message"=>"failed"],200);
        }
    }
}
