<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Http\Requests\GiftRewardSettingRequest;
use App\Http\Requests\GiftCardAddRequest;
use App\Http\Requests\GiftCardEditRequest;
use App\Models;
use App\Models\SuperAdminSiteSetting;
use App\Models\GiftCard;
use App\Models\Company;
use App\Models\Cms;
use App\Models\CompanyLocation;
use App\Models\CompanyAdmin;
use App\Models\User;
use App\Models\EmployeePointRedemption;
use App\Models\CompanyEmployeeLocation;
use App\Models\Giftsettlements;
use Auth;
use Validator;
use Illuminate\Http\Request;
use App\Services\DefaultServices;
use Exception;
use Yajra\Datatables\Datatables;
use Mail;

class GiftRewardController extends Controller {

	protected $defaultServices;

    public function __construct(DefaultServices $defaultServices)
    {
        $this->defaultServices = $defaultServices;
    }

    public function rewardSetting()
    {
    	$reward['reward-amount'] = SuperAdminSiteSetting::firstWhere('slug', 'reward-amount');
        $reward['minimum-redeemable-value'] = SuperAdminSiteSetting::firstWhere('slug', 'minimum-redeemable-value');

        return view('superAdmin.giftReward.rewardSetting', compact('reward'));
    }

    public function saveRewardSetting(GiftRewardSettingRequest $request) 
    {
    	try{
            $request->validated();

            $siteSetting = SuperAdminSiteSetting::firstOrNew(['slug' => 'reward-amount']);
            $siteSetting->setting_value = trim($request->reward_amount);
            $siteSetting->setting_name = "Reward amount";
            $siteSetting->is_text = 1;
            $siteSetting->save();

            $siteSetting = SuperAdminSiteSetting::firstOrNew(['slug' => 'minimum-redeemable-value']);
            $siteSetting->setting_value = trim($request->minimum_redeemable_value);
            $siteSetting->setting_name = "Minimum redeemable value";
            $siteSetting->is_text = 1;
            $siteSetting->save();

            $request->session()->flash('success-message', 'Conversion rate updated successfully');
            return redirect()->route('superAdmin.rewardSetting');
        }
        catch (Exception $ex) {
            return redirect()->back()->withErrors(['error-messsage' => [$ex->getMessage()]]);
        }
    }

    public function giftCardList(Request $request)
    {
        if($request->ajax()) {
            $filters   = [];
            $filters['is_delete'] = 0;
            $allData = GiftCard::where($filters);
            //dd($allData);
            return datatables($allData)->make(true);
        }

        return view('superAdmin.giftReward.giftCardList');
    }

    public function addGiftCard() 
    {
        return view('superAdmin.giftReward.giftCard');
    }

    public function editGiftCard(Request $request) 
    {
        $giftcard_details = GiftCard::find($request->id);
        return view('superAdmin.giftReward.editGiftCard',compact('giftcard_details'));
    }

    public function updateGiftCard(GiftCardEditRequest $request) 
    {
        try{
            $request->validated();
            $gift_image = $request->file('gift_image');

            $giftcardDetails = GiftCard::find($request->id);   
            $giftcardDetails->retailer_name = trim($request->retailer_name) ?: NULL;
            $giftcardDetails->gift_desc = trim($request->gift_desc) ?: NULL;

            if($gift_image) {
                $rootFolderPath = public_path('/storage/images/giftcard');
                if($giftcardDetails->gift_image) {
                    $this->defaultServices->unlinkImg($rootFolderPath, $giftcardDetails->gift_image);
                }
                $giftcardDetails->gift_image = $this->defaultServices->imgUpload($rootFolderPath, $gift_image);
            }

            $update = $giftcardDetails->save();

            if($update) {
                $request->session()->flash('success-message', 'Giftcard updated successfully');  
                return redirect()->back();
            }else {
                return redirect()->back()->withErrors(['error-messsage' => ['Sorry, some problem occurred. Please try again!']]);
            }
        }
        catch (Exception $ex) {
            return redirect()->back()->withErrors(['error-messsage' => [$ex->getMessage()]]);
        }
    }

    public function saveGiftCard(GiftCardAddRequest $request) 
    {
    	try{
            $request->validated();
            $gift_image = $request->file('gift_image');
            
            $giftArr['retailer_name'] = trim($request->retailer_name) ?: NULL;
            $giftArr['gift_desc'] = trim($request->gift_desc) ?: NULL;

            if($gift_image) {
                $rootFolderPath = public_path('/storage/images/giftcard');
                $giftArr['gift_image'] = $this->defaultServices->imgUpload($rootFolderPath, $gift_image);
            }

            $insert = GiftCard::create($giftArr);

	        if($insert) {
	        	$request->session()->flash('success-message', 'Giftcard added successfully');  
	        	return redirect()->back();
	        }else {
	        	return redirect()->back()->withErrors(['error-messsage' => ['Sorry, some problem occurred. Please try again!']]);
	        }
        }
        catch (Exception $ex) {
            return redirect()->back()->withErrors(['error-messsage' => [$ex->getMessage()]]);
        }

    }

    public function redeemHistory(Request $request)
    {
        $filters['is_active'] = 1;
        $filters['is_delete'] = 0;
        $companyData = Company::where($filters)->get();
        $locationData = CompanyLocation::where($filters)->get();
        $employeeData = User::where($filters)->get();
        return view('superAdmin.giftReward.redeemHistory',compact('companyData','locationData','employeeData'));
    }

    public function getRedeemHistory(Request $req){
        $company_id = $req->company_id;
        $company_location_id= $req->company_location_id;
        $user_id= $req->user_id;
        if($req->ajax()) {
            $redeemHistoryQuery = EmployeePointRedemption::leftJoin('companies', function ($join) {
              $join->on('employee_point_redemptions.company_id', '=', 'companies.id');
            })
            ->leftJoin('gift_cards', function ($join) {
              $join->on('gift_cards.id', '=', 'employee_point_redemptions.giftcard_id');
            })
            ->leftJoin('users', function ($join) {
              $join->on('users.id', '=', 'employee_point_redemptions.user_id');
            })
            ->select(
                'employee_point_redemptions.id',
                'companies.company_name as company_name',
                'gift_cards.retailer_name as giftcard_name',
                'employee_point_redemptions.redeem_point as redeem_point',
                'employee_point_redemptions.redeem_amount as redeem_amount',
                'employee_point_redemptions.is_active as settle_status',
                'employee_point_redemptions.is_settle as is_settle',
                'users.name as user_name',
                'users.email as user_email',
            )
            ->where('employee_point_redemptions.is_active',1)
            ->where('employee_point_redemptions.is_delete',0);
            if($company_id){
               $redeemHistoryQuery->where('employee_point_redemptions.company_id',$company_id);
            }
            if($company_location_id){
               $redeemHistoryQuery->where('employee_point_redemptions.company_location_id',$company_location_id);
            }
            if($user_id){
               $redeemHistoryQuery->where('employee_point_redemptions.user_id',$user_id);
            }
            $redeemHistories=$redeemHistoryQuery->get();
            //dd($redeemHistories);
            return Datatables::of($redeemHistories)
            ->addIndexColumn()
            ->addColumn('employee_name', function($row){                
                return $row->user_name.'<br>'.$row->user_email;
            })
            ->addColumn('company_name', function($row){                
                return $row->company_name;
            })
            ->addColumn('giftcard_name', function($row){                
                $giftcard_name= $row->giftcard_name;
                if(strlen($giftcard_name) > 25){
                  $giftcard_name = substr($giftcard_name, 0, 25) . '...';
                }
                return $giftcard_name;
            })
            ->addColumn('redeem_point', function($row){                
                return $row->redeem_point;
            })
            ->addColumn('redeem_amount', function($row){                
                return $row->redeem_amount;
            })
            ->addColumn('is_settle', function($row){ 
                if($row->is_settle != 1){
                    $button = '<a class="btn btn-primary btn-pill" href="'.url('superadmin/managegiftcard/settlesystem/'.encript_decript_data($row->id,'encript' ,2)).'">Action Required</a>';
                    return $button;
                }else{
                    $button = '<a class="btn btn-primary btn-pill" style="background: #14c440;" href="'.url('superadmin/managegiftcard/settlesystem/'.encript_decript_data($row->id,'encript' ,2)).'">Paid</a>';
                   // $button = '<a class="btn btn-primary btn-pill" href="'.url('superadmin/managegiftcard/settlesystem/'.encript_decript_data($row->id,'encript' ,2)).'">Settled</a> &nbsp; <a data-id="'.$row->id.'" class="btn btn-primary btn-pill resend" href="javascript:void(0)">Resend</a>';
                    return $button;                    
                }
                

            })
            ->addColumn('id', function($row){                
                return $row->id;
            })
            ->rawColumns(['employee_name', 'company_name', 'giftcard_name' , 'redeem_point' , 'redeem_amount', 'is_settle' , 'id'])
            ->make(true);
        }
    }

    public function get_company_location(Request $req){
        $company_id=$req->company_id;
        $company_locations=CompanyLocation::where('company_id',$company_id)->get();
        $company_locations_html='<option value="">Search By Location</option>';
        if($company_locations !=null){
            foreach($company_locations as $company_location_row){
                $company_locations_html.='<option value="'.$company_location_row->id.'">'.$company_location_row->name.'</option>';
            }

        }
        $total_redeem_points=EmployeePointRedemption::where('company_id',$company_id )->sum('redeem_point');
        $company_location_employee_ids=CompanyEmployeeLocation::where('company_id',$company_id)->pluck('user_id')->toArray();
        $company_location_employees=User::whereIn('id',$company_location_employee_ids)->get();
        $company_location_employees_html='<option value="">Search By Employee Name</option>';
        if($company_location_employees !=null){
            foreach($company_location_employees as $company_location_employee_row){
                $company_location_employees_html.='<option value="'.$company_location_employee_row->id.'">'.$company_location_employee_row->name.'</option>';
            }

        }
        return array($company_locations_html,$total_redeem_points,$company_location_employees_html);
    }

    public function get_company_location_employee(Request $req){
        $location_id=$req->location_id;
        $company_id=$req->company_id;
        if($location_id!=''){
          $company_location_employee_ids=CompanyEmployeeLocation::where('location_id',$location_id)->pluck('user_id')->toArray();
        }else{
          $company_location_employee_ids=CompanyEmployeeLocation::where('company_id',$company_id)->pluck('user_id')->toArray();    
        }
        $company_location_employees=User::whereIn('id',$company_location_employee_ids)->get();
        $company_location_employees_html='<option value="">Search By Employee Name</option>';
        if($company_location_employees !=null){
            foreach($company_location_employees as $company_location_employee_row){
                $company_location_employees_html.='<option value="'.$company_location_employee_row->id.'">'.$company_location_employee_row->name.'</option>';
            }

        }
        if($location_id!=''){
          $total_redeem_points=EmployeePointRedemption::where('company_location_id',$location_id )->sum('redeem_point');
        }else{
          $total_redeem_points=EmployeePointRedemption::where('company_id',$company_id )->sum('redeem_point');
        }
        return array($company_location_employees_html,$total_redeem_points);
    }

    public function get_company_location_employee_points(Request $req){
        $company_id=$req->company_id;
        $location_id=$req->location_id;
        $employee_id=$req->employee_id;
        if($company_id!='' && $location_id!='' && $employee_id!=''){
          $total_redeem_points=EmployeePointRedemption::where('company_id',$company_id )->where('company_location_id',$location_id)->where('user_id',$employee_id)->sum('redeem_point');
        }else if($company_id!='' && $location_id!=''){
          $total_redeem_points=EmployeePointRedemption::where('company_id',$company_id )->where('company_location_id',$location_id)->sum('redeem_point');
        }else if($company_id!='' && $employee_id!=''){
          $total_redeem_points=EmployeePointRedemption::where('company_id',$company_id )->where('user_id',$employee_id)->sum('redeem_point');
        }else{
          $total_redeem_points=EmployeePointRedemption::where('company_id',$company_id )->sum('redeem_point');
        }
        return $total_redeem_points;
    }
    
    public function settleSystem(Request $req){
         $id = encript_decript_data($req->id,'decript' ,2);         
         $getRedeemData = EmployeePointRedemption::leftJoin('companies', function ($join) {
              $join->on('employee_point_redemptions.company_id', '=', 'companies.id');
            })  
            ->leftJoin('gift_cards', function ($join) {
              $join->on('gift_cards.id', '=', 'employee_point_redemptions.giftcard_id');
            })  
            ->leftJoin('users', function ($join) {
              $join->on('users.id', '=', 'employee_point_redemptions.user_id');
            })
            ->select(
                'employee_point_redemptions.id',
                'companies.company_name as company_name',    
                'gift_cards.retailer_name as giftcard_name',          
                'employee_point_redemptions.redeem_point as redeem_point',
                'gift_cards.retailer_name as giftcard_name',
                'employee_point_redemptions.redeem_amount as redeem_amount',
                'employee_point_redemptions.is_settle as is_settle',
                'users.name as user_name',
                'users.email as user_email',
                'users.id as user_id',
            )
            ->where('employee_point_redemptions.is_active',1)
            ->where('employee_point_redemptions.is_delete',0)
            ->where('employee_point_redemptions.id',$id)->first();

            $policyData = Cms::where('slug','gift-card-policy')->first();
            $giftSettlements = Giftsettlements::where('employee_point_redemption_id', $id)->first();   
            //dd($giftSettlements);  
           
        return view('superAdmin.giftReward.settlement',compact('getRedeemData','policyData','giftSettlements'));

    }
    public function settle(Request $req){

    try{            
        
        if($req->isMethod('post')) {
           $validator = Validator::make($req->all(), [
                'couponcode' => 'required'                
            ]);
           if ($validator->fails()) {
            $message = $validator->errors();
                return redirect()->back()->withErrors($message);
            }

            $to_email = $req->email1;
            $to_name  = $req->user_name;
            $subject = 'User Redeem Settle';
            $mail_data = array(
                'couponcode'   => $req->couponcode,               
                'privacy_pilicy'   => $req->privacy_pilicy                
            ); 
            //dd($mail_data );
            Mail::send('emails.redemptionEmail', $mail_data, function($message) use($to_name, $to_email, $subject) {
                $message->to($to_email, $to_name??'4e Super Admin')->subject($subject);
                $message->from(env('MAIL_FROM_ADDRESS', ''), env('MAIL_FROM_NAME', '4e'));
                //$message->from('noreply@gmail.com', 'Foure WebAdmin');
            });
            $giftsettlements = 
               [
                   'employee_point_redemption_id' => $req->id,
                   'employee_id' => $req->user_id,  
                   'coupon_code' => $req->couponcode,                    
                   'privacypolicy_text' => $req->privacy_pilicy,  
                   'settlement_date' => date('Y-m-d h:i:s'),  
                ];              
            $result = Giftsettlements::create($giftsettlements);
            if($result){
                EmployeePointRedemption::where('id', $req->id)->update(['is_settle' => 1]);
            }

            $req->session()->flash('success-message', 'Coupon Code send successfully');
        }
        return redirect()->route('superAdmin.redeemHistory');

        }catch(Exception $e){
            return redirect()->back()->withErrors(['error-messsage' => [$e->getMessage()]]);
        }

    }

}
