<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Http\Requests\CompanyLicenseTypeRequest;
use App\Http\Requests\CompanyRegistrationRequest;
use App\Models\CompanyEstablishmentType;
use App\Models\CompanyLicenceType;
use Yajra\DataTables\DataTables;
use App\Models\CompanyAddress;
use App\Models\CompanyLicence;
use Illuminate\Http\Request;
use App\Models\CompanyBank;
use App\Models\Language;
use App\Models\Currency;
use App\Models\Company;
use App\Models\Country;
use App\Models\State;
use App\Models\City;
use App\Models\CompanyImage;
use App\Models\Timezone;
use App\Models\TimeFormat;
use App\Models\DateFormat;
use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class CompanyController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:company-list|company-create|company-edit|company-delete', ['only' => ['index','store']]);
    }

  public function index(Request $request)
  {
    if (!$this->modulePermissionCheck('COMPANY')) {
        abort(404);
    }

    $data = Company::with('getCompanyName')
      ->select(['id','name','email','office_type','mobile_number','phone_number','status','is_default']);

    if ($request->ajax()) {
      $sort_by      = $request->get('sortby');
      $sort_type    = $request->get('sorttype');
      $search_query = $request->get('query');

      $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
            return $query->where('name', 'like', '%'.$search_query.'%');
        })
        ->paginate($sort_by);

      return view('company.table', compact('data'));
    }

    $data = $data->paginate(10);

    return view('company.index',compact('data'));
  }

  public function create()
  {
    $company_address         = \Session::get('company_data')['companies_addresses'];

    $country_id          = $company_address->country_id ?? '';
    $countryCode         = $company_address->country_code ?? 'us';

    $Country             = Country::select(['id','name'])->get();
    $currencies          = Currency::select(['id','currency', 'country_id'])->with('countries')->get();
    $languages           = Language::select(['id','name'])->get();
    $companyLicense      = CompanyLicenceType::select(['id','license_type_name'])->get();
    $establishment_types = CompanyEstablishmentType::select(['id','name','is_default'])->where('status', 1)->get();

    $time_zone           = Timezone::select('id','name','details')->get();
    $time_format         = TimeFormat::select('id','time_format_name','time_format_details')->get();
    $date_format         = DateFormat::select('id','format','format_details')->get();
    return view('company.add',compact(
        'Country',
        'languages',
        'currencies',
        'country_id',
        'countryCode',
        'companyLicense',
        'company_address',
        'establishment_types',
        'time_zone',
        'time_format',
        'date_format',
    ));
  }

  public function getstate(Request $request)
  {
    $getState = State::select(['id','name'])->where('country_id',$request->country)->get();

    foreach($getState as $list)
    {
      if($request->stateid==$list->id)
      {
        echo '<option value="'.$list->id.'" selected>'.$list->name.'</option>';
      }
      else
      {
        echo '<option value="'.$list->id.'">'.$list->name.'</option>';
      }
    }
  }

  public function getcity(Request $request)
  {
      if(isset($request->states_id) && $request->states_id != 0)
      {
        $getCity = City::select(['id','name'])->where('state_id',$request->states_id)->get();
      }
      else
      {
        $getCity = City::select(['id','name'])->limit(20)->get();
      }

      foreach($getCity as $list)
      {
        if($request->cityid == $list->id)
        {
          echo '<option value="'.$list->id.'" selected>'.$list->name.'</option>';
        }
        else
        {
          echo '<option value="'.$list->id.'">'.$list->name.'</option>';
        }
      }
  }

  public function getcityConsignor(Request $request)
  { 
      $searchTerm = $request->search_text;
        $results   = City::select([
            'cities.*',
            'cities.id as id',
            'cities.name as name',
            // 'states.id',
            // 'states.country_id',
            'countries.id as country_id',
        ])
        ->leftjoin('states','states.id','cities.state_id')
        ->leftjoin('countries','countries.id','states.country_id')
        ->where('countries.id',$request->country_id)
        ->orderBy('cities.name','asc')
        ->where(function ($query) use ($searchTerm) {
                        $query->where('cities.name', 'LIKE', $searchTerm . '%');
                    })
                    ->get();

        return response()->json(['result' => $results, 'status' => true]);
  }

  public function getcountrycode(Request $request)
  {
    $company_address = \Session::get('company_data')['companies_addresses'];

    $countryCode = $company_address->country_code ?? 'us';

    if (isset($request->country) && $request->country != 0) {
        $getCountryCode = Country::where('id', $request->country)->value('code');
        $getCountryCode = $getCountryCode != '' ? $getCountryCode : $countryCode;
        return response()->json($getCountryCode);
    }

    return response()->json($countryCode);
  }

  public function store(Request $request)
  {
        $validator = \Validator::make($request->all(), [
            'name'         =>'required|unique:companies',
            'office_type'  =>'required',
            'country_id'   =>'required',
            'phone_number' =>'required|unique:companies|max:16|min:10',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $logo = "";
        //return $request;die;

      /********************* Company Basic Registration *********************/
      $dataCompany = [
        'name'                  =>$request->name,
        'email'                 =>$request->email,
        'code'                  => strtoupper(str_replace(' ', '_', $request->name)),
        'branch_name'           =>$request->branch_name,
        'branch_code'           =>$request->branch_code,
        'office_type'           =>$request->office_type,
        'mobile_number'         =>$request->mobile_number,
        'whatsapp_no'           =>$request->whatsapp_no,
        'phone_number'          => str_replace(' ', '', $request->phone_number),
        'letter_head'           =>$request->letter_head,
        'establishment_type_id' =>$request->establishment_type_id,
        'website'               =>$request->website,
        'deals_in'              =>$request->deals_in,
        'tag_line'              =>$request->tag_line,
        'logo'                  =>$logo,
        'date_format'           =>$request->date_format,
        'time_format'           =>$request->time_format,
        'time_zone'             =>$request->time_zone,
        'language_id'           =>$request->language_id,
        'currency_id'           =>$request->currency_id,
      ];

      $company = Company::create($dataCompany);

      // company basic registration section
      $company_id = $company->id;

      /********************* Company Address Registration *********************/
      $company_address = [
        'company_id'         =>$company_id,
        'address_type_id'    =>5,
        'address_1'          =>$request->address_1,
        'country_id'         =>$request->country_id,
        'state_id'           =>$request->state_id,
        'city_id'            =>$request->city_id,
        'location_longitude' =>$request->location_longitude,
        'google_place_link'  =>$request->google_place_link,
        'location_latitude'  =>$request->location_latitude,
        'pin_code'           =>$request->pin_code,
        'is_default'         =>1,
        'priority'           =>1,
      ];

    CompanyAddress::create($company_address);
    $session = $this->setCompanySession();

    if ($request->ajax()) {
        return response()->json([
            'success' => true,
            'message' => 'Company created successfully',
            'data'    => $company
        ]);
    }

    return redirect('companies')->with('success','Company created successfully.');
  }

      /****************license type add*************/

     public function edit($id)
     {
        $company_basic  = Company::with('getCompanyAddress')->find($id);

        if($company_basic =='')
        {
          return redirect('/companies')->with('error',"Company is Not Avaiable");
        }
        else
        {
            $data['currencies']  = Currency::select(['id','currency', 'country_id'])->with('countries')->get();
            $data['languages']   = Language::select(['id','name'])->get();
            $data['Country']     = Country::select(['id','name'])->get();
            $companyLicense      = CompanyLicenceType::select(['id','license_type_name'])->get();
            $establishment_types = CompanyEstablishmentType::select(['id','name','is_default'])
                                    ->where('status', 1)
                                    ->get();

            $data['company_basic']       = $company_basic;
            $data['companyLicense']      = $companyLicense;
            $data['establishment_types'] = $establishment_types;

            $company_address = \Session::get('company_data')['companies_addresses'];

            $data['country_id']  = $data['company_address']->country_id ?? '';
            $data['countryCode'] = $data['company_address']->country_code ?? 'us';

            $data['time_zone']   = Timezone::all();
            $data['time_format'] = TimeFormat::all();
            $data['date_format'] = DateFormat::all();

            return view('company.edit',$data);
        }
     }


     public function show($id)
     {
        $company_basic = Company::with('language')->with('currency')->with('getZone')->find($id);

        if ($company_basic =='') {
          return redirect('/companies')
            ->with('error',"Company is Not Avaiable");
        } else {
            $Country         = Country::select(['id','name'])->get();
            $company_address = CompanyAddress::where('company_id',$id)->first();
            $company_bank    = CompanyBank::where('company_id',$id)->first();
            $Country         = Country::select(['id','name'])->get();

            $company_basic->logo_url = getTempUrl($company_basic->logo);
            $data['company_basic']   = $company_basic;
            $data['Country']         = $Country;
            $data['company_address'] = $company_address;
            $data['company_bank']    = $company_bank;
            $data['Country']         = $Country;

            return view('company.show',$data);
        }
     }

     public function update($id,Request $request)
     {

        $validator = \Validator::make($request->all(), [
            'name'         => 'required|unique:companies,name,'.$id,
            'email'        =>'required|email',
            'office_type'  =>'required',
            'country_id'   =>'required',
            'phone_number' =>'required|unique:companies,phone_number,'.$id .'|max:16|min:10',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $input         = $request->all();
        $company_basic = Company::find($id);

        if ($request->hasFile('logo')) {
            $path     = "company_logo";
            $response = uploadImage($path,$request->logo,$company_basic->logo);

            if ($response['status'] == true) {
                $logo = $response['file_name'];
            } else {
                $session = $this->setCompanySession();
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }
        else
        {
          $logo=$company_basic->logo;
        }

        /********************* Company Basic Registration *********************/
        $dataCompany=[
            'name'                  =>$request->name,
            'email'                 =>$request->email,
            'code'                  => strtoupper(str_replace(' ', '_', $request->name)),
            'branch_name'           =>$request->branch_name,
            'branch_code'           =>$request->branch_code,
            'office_type'           =>$request->office_type,
            'mobile_number'         =>$request->mobile_number,
            'phone_number'          => str_replace(' ', '', $request->phone_number),
            'whatsapp_no'           =>$request->whatsapp_no,
            'letter_head'           =>$request->letter_head,
            'website'               =>$request->website,
            'establishment_type_id' =>$request->establishment_type_id,
            'deals_in'              =>$request->deals_in,
            'tag_line'              =>$request->tag_line,
            'logo'                  =>$logo,
            'date_format'           =>$request->date_format ?? '',
            'time_format'           =>$request->time_format ?? '',
            'time_zone'             =>$request->time_zone ?? '',
            'language_id'           =>$request->language_id ?? '',
            'currency_id'           =>$request->currency_id ?? '',
        ];
          $company_basic->update($dataCompany);

          /********************* Company Address Update *********************/
          $getcompanyaddress = CompanyAddress::where('company_id',$id)->whereNull('deleted_at')->where('is_default',1)->first();
          if($getcompanyaddress)
          {
            $company_address=[
              'address_1'          =>$request->address_1,
              'country_id'         =>$request->country_id,
              'state_id'           =>$request->state_id,
              'city_id'            =>$request->city_id,
              'location_longitude' =>$request->location_longitude,
              'google_place_link'  =>$request->google_place_link,
              'location_latitude'  =>$request->location_latitude,
              'pin_code'           =>$request->pin_code,];
             $getcompanyaddress->update($company_address);
          }
          else
          {
            $company_address=[
              'company_id'         =>$id,
              'address_1'          =>$request->address_1,
              'country_id'         =>$request->country_id,
              'state_id'           =>$request->state_id,
              'city_id'            =>$request->city_id,
              'location_longitude' =>$request->location_longitude,
              'google_place_link'  =>$request->google_place_link,
              'location_latitude'  =>$request->location_latitude,
              'pin_code'           =>$request->pin_code,
              'is_default'         =>1,
            ];
             CompanyAddress::create($company_address);
          }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Company updated successfully',
            ]);
        }

        return redirect('companies')->with('success','Company updated successfully');
     }

    public function changeStatus(Request $request)
    {
        if ($request->ajax())
        {
            $data = array('status' => $request->status );
            $Update = Company::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Company status successfully change'],
                    'data'=>[
                        'redirect'=>'/companies/',
                        'reload'=>true,
                    ]
                ]);
            }
            else{
                return response()->json([
                    'success'=>false,
                    'message'=>['Error for change status'],
                    'data'=>[
                        'redirect'=>'',
                    ]
                ]);
            }
        }
    }

    public function delete(Request $request)
    {
        $about = Company::find($request->id);

        if ($about->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $about->delete();

        $Redirect = 'companies';
        $session = $this->setCompanySession();
        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
    }

    public function deleteLicense(Request $request)
    {
      $license=CompanyLicence::find($request->id);
      $license->delete();
      echo 1;
    }
    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status);
            $count  = Company::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Company!'],
                    'data'    => []
                ]);
            }

            $Update = Company::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Company default status successfully changed.'],
                    'data'=>[
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

    public function companyBanks($id)
    {
        $data = CompanyBank::where('company_id', $id)->whereNull('deleted_at')->get();

        return view('company-banks.table', compact('data'));
    }

    /**
     * Fetch the specified resource addresses from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function addresses($id)
    {
      $data = CompanyAddress::select([
          'companies_addresses.*',
          'countries.name as country',
          'address_types.name as address_types',
          'states.name as state',
          'cities.name as city',
        ])
        ->leftjoin('address_types', 'address_types.id', 'companies_addresses.address_type_id')
        ->leftjoin('countries', 'countries.id', 'companies_addresses.country_id')
        ->leftjoin('states', 'states.id', 'companies_addresses.state_id')
        ->leftjoin('cities', 'cities.id', 'companies_addresses.city_id')
        ->where('company_id', $id)
        ->whereNull('deleted_at')
        ->orderBy('priority','ASC')
        ->get();

      return view('company-addresses.table', compact('data'));
    }

    /**
     * Fetch the specified resource addresses from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function documents($id)
    {
      $data = CompanyLicence::select([
          'companies_license.*',
          'companies_license_type.license_type_name'
        ])
        ->leftjoin('companies_license_type', 'companies_license_type.id', 'companies_license.license_type_id')
        ->where('companies_license.company_id', $id)
        ->whereNull('companies_license.deleted_at')
        ->orderBy('companies_license.priority','ASC')
        ->get();

      return view('company-documents.table', compact('data'));
    }

    public function selectImage($id)
    {
        return view('company.image', compact('id'));
    }

    public function storeImage(Request $request)
    {
      $company = Company::find($request->company_id);

      if ($request->hasFile('file')) {
        $path     = "company_logo";
        $response = uploadImage($path,$request->file,$company->logo);

        if ($response['status'] == true) {
            $logo = $response['file_name'];
            $company->update(['logo'=>$logo]);
        } else {
            if ($request->ajax()) {
                $session = $this->setCompanySession();
                return response()->json([
                    'success' => false,
                    'message' => $response['message'],
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $response['message']);
        }
      }

      return response()->json([
          'success' => true,
          'message' => ['Uploaded successfully'],
          'data'    => [
              'reload' => true,
          ]
      ]);
    }
    public function setCompanySession()
    {
        $company_address = CompanyAddress::select(
                'countries.currency_symbol',
                'countries.formats',
                'countries.code as country_code',
                'companies_addresses.*',
                'country_currencies.id as currency_id',
                'country_currencies.code as currency_code',
                'country_currencies.currency',
            )
            ->leftjoin('countries', 'countries.id', 'companies_addresses.country_id')
            ->leftjoin('country_currencies', 'country_currencies.country_id', 'companies_addresses.country_id')
            ->where('companies_addresses.company_id', Auth::user()->company_id)
            ->first();

        $company_data = Company::select('companies.*', 'timezones.name as time_zone')
            ->leftjoin('timezones', 'timezones.id', 'companies.time_zone')
            ->find(Auth::user()->company_id)
            ->toArray();

        $company_data['auth_currency']       = $company_address->currency_symbol ?? 'USD';
        $company_data['auth_formats']        = $company_address->formats ?? 'm-d-Y';
        $company_data['companies_addresses'] = $company_address;

        Session::put('company_data', $company_data);

        $HeadOfficeData = Company::select('name', 'id', 'logo')->where('office_type', 'head_office')->where('status', '1')->first();

        Session::put('HeadOfficeData', $HeadOfficeData);
    }
    public function companyImage($id)
    {
        $data = CompanyImage::where('company_id', $id)->whereNull('deleted_at')->get();

        return view('company-images.table', compact('data'));
    }
}
