<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use App\Models\CampaignEmails;
use App\Models\Campaigns;
use App\Models\CandidateVideoInterviews;
use App\Models\Question;
use App\Models\RoleQuestions;
use App\Models\Settings;
use App\Models\User;
use App\Models\VideoInterviewCategoriesVideos;
use App\Models\Introduction_content;
use App\Models\Introduction_desc;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use File;
use Illuminate\Support\Facades\Mail;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        define('PAGE_LIMIT', 30);
    }

    public function index()
    {
        $data = array();
        $data['title'] = 'Anantha Interviews-Dashboard';
        $data['active_menu'] = 'dashboard';
        $data['sub_active_menu'] = 'dashboard';
        return view('backend.dashboard', $data);
    }

    public function users()
    {
        $data = array();
        $data['title'] = 'Anantha Interviews-Users';
        $data['active_menu'] = 'users';
        $data['sub_active_menu'] = 'users';
        $data['questions'] = Question::where('id', '!=', 9)->orderBy('id', 'asc')->get();
        $data['records'] = User::where('role_id', '!=', 404)->orderBy('id', 'desc')
            ->paginate(PAGE_LIMIT);
        return view('backend.users', $data);
    }

    public function completedUsers($id = '')
    {
        $data = array();
        $data['title'] = 'Anantha Interviews-Users';
        $data['active_menu'] = 'completed_users';
        $data['sub_active_menu'] = 'completed_users';
        if ($id != '') {
            $data['questions'] = Question::where('id', '!=', 9)->orderBy('id', 'asc')->get();
            $userInfo = User::where('id', $id)->with('getCandidate')->first();
            $data['role_questions'] = RoleQuestions::where('role_id', $userInfo->role_id)->orderBy('id', 'asc')->get();


            if (isset($userInfo->getRecords) && count($userInfo->getRecords) > 0) {
                $userInfo->getRecords->map(function ($q) {

                    if (isset($q->getRefVideo)) {
                        if ($q->getRefVideo->video_url != '') {
                            $q->getRefVideo->video_url_file = VideoInterviewCategoriesVideos::uploadDir('url') . '/' . $q->getRefVideo->video_url;
                        } else {
                            $q->getRefVideo->video_url_file = null;
                        }


                        if ($q->video_file != '') {
                            $q->video_file_url = CandidateVideoInterviews::uploadDir('url') . '/' . $q->video_file;
                        } else {
                            $q->video_file_url = null;
                        }
                    }


                });
            }


            $data['userInfo'] = $userInfo;


            return view('backend.users.completed_userInfo', $data);

        } else {
            $data['records'] = User::where('flag', 1)->whereNotIn('role_id', [404])->orderBy('id', 'desc')
                ->paginate(PAGE_LIMIT);
            return view('backend.users.completed_users', $data);
        }

    }

    public function inCompleteUsers($id = '')
    {
        $data = array();
        $data['title'] = 'Anantha Interviews-Users';
        $data['active_menu'] = 'incompleted_users';
        $data['sub_active_menu'] = 'incompleted_users';
        if ($id != '') {
            $data['questions'] = Question::where('id', '!=', 9)->orderBy('id', 'asc')->get();
            $userInfo = User::where('id', $id)->first();
            $data['role_questions'] = RoleQuestions::where('role_id', $userInfo->role_id)->orderBy('id', 'asc')->get();

            if (isset($userInfo->getRecords) && count($userInfo->getRecords) > 0) {
                $userInfo->getRecords->map(function ($q) {

                    if ($q->getRefVideo->video_url != '') {
                        $q->getRefVideo->video_url_file = VideoInterviewCategoriesVideos::uploadDir('url') . '/' . $q->getRefVideo->video_url;
                    } else {
                        $q->getRefVideo->video_url_file = null;
                    }


                    if ($q->video_file != '') {
                        $q->video_file_url = CandidateVideoInterviews::uploadDir('url') . '/' . $q->video_file;
                    } else {
                        $q->video_file_url = null;
                    }
                });
            }

            $data['userInfo'] = $userInfo;

            return view('backend.users.incompleted_userInfo', $data);
        } else {
            $data['records'] = User::where('flag', 0)->whereNotIn('role_id', [404])->orderBy('id', 'desc')
                ->paginate(PAGE_LIMIT);
            return view('backend.users.incompleted_users', $data);
        }
    }

    public function settings(Request $request)
    {
        if ($request->isMethod('post')) {
            $requestData = $request->all();
            $settings = Settings::first();
            if (!empty($settings)) {
                $imageRule = empty($settings->logo) ? 'required' : '';
            } else {
                $imageRule = 'required';
            }

            $this->validate(request(), [
                'title' => 'required',
                'logo' => $imageRule
            ], [
                'title.required' => 'Please enter name',
                'logo.required' => 'Please enter logo'
            ]);

            if (!empty($settings)) {
                if ($request->hasFile('logo')) {
                    $requestData['logo'] = Settings::uploadImage($request, 'logo', $settings->logo);
                }
                if ($request->hasFile('video_logo')) {
                    $requestData['video_logo'] = Settings::uploadImage($request, 'video_logo', $settings->video_logo);
                }
                $settings->update($requestData);
                $mes = 'settings updated successfully!';
            } else {
                if ($request->hasFile('logo')) {
                    $requestData['logo'] = Settings::uploadImage($request, 'logo');
                }
                if ($request->hasFile('video_logo')) {
                    $requestData['video_logo'] = Settings::uploadImage($request, 'video_logo');
                }
                Settings::create($requestData);
                $mes = 'settings Added successfully!';
            }
            return redirect()->route('admin.settings')->with('flash_message', $mes);

        } else {
            $data = array();
            $data['active_menu'] = 'settings';
            $data['sub_active_menu'] = 'settings';
            $data['record'] = Settings::first();
            $data['title'] = 'settings';
            return view('backend.settings', $data);
        }
    }

    public function deletelogo(Request $request)
    {
        $image = Settings::findOrFail($request['image']);

        File::delete('uploads/settings/' . $image->logo);

        $update_data = array();
        $update_data['logo'] = '';
        $image->update($update_data);
        exit();
    }

    public function deletevideologo(Request $request)
    {
        $image = Settings::findOrFail($request['image']);

        File::delete('uploads/settings/' . $image->video_logo);

        $update_data = array();
        $update_data['video_logo'] = '';
        $image->update($update_data);
        exit();
    }


    public function emailsNotifications(Request $request)
    {
        if ($request->isMethod('post')) {
            $requestData = $request->all();

            $this->validate(request(), [
                'campaign_title' => 'required',
                'senders' => 'required',
                'template' => 'required',
                'preview' => 'required',
            ], [
                'campaign_title.required' => 'Please enter title',
                'senders.required' => 'Please enter senders info',
                'template.required' => 'Please select template',
                'preview.required' => 'Please enter template preview',
            ]);

            $senders = explode(',', $requestData['senders']);

            $from_address = $_ENV['MAIL_FROM_ADDRESS'];

            $from_name = $_ENV['MAIL_FROM_NAME'];

            $requestData['campaign_type']= $requestData['template'];
            $requestData['campaign_content']= $requestData['preview'];
            $campaign_id=Campaigns::create($requestData)->id;

            foreach ($senders as $sender) {

                $email = $sender;
                $otp = rand ( 10000 , 99999 );
                $original = ["{{url}}", "{{email}}", "{{otp}}"];
                $updated = [url('startnow'), $email, $otp];

                $preview = str_replace($original, $updated, $requestData['preview']);

                $inputdata=array();
                $inputdata['campaign_id']=$campaign_id;
                $inputdata['email_id']=$email;
                $inputdata['invitation_code']=$otp;
                CampaignEmails::create($inputdata);

                Mail::send([], [], function ($message) use ($email, $from_address, $from_name, $preview) {
                    $message->from($from_address, $from_name);
                    $message->to($email, $email);
                    $message->subject("interview invitation email!");
                    $message->setBody($preview, 'text/html');
                });

            }

            $mes = 'Email sent successfully';

            return redirect()->route('admin.emails_notifications')->with('flash_message', $mes);

        } else {
            $data = array();
            $data['active_menu'] = 'emails_notifications';
            $data['sub_active_menu'] = 'emails_notifications';
            $data['title'] = 'Emails Notifications';
            return view('backend.emails_notifications', $data);
        }
    }

    public function gettemplatecontent(Request $request)
    {
        $file = File::get(base_path() . "/resources/views/backend/emails/" . $request['template'] . ".blade.php", "r");
        echo $file;
    }
	public function introduction_content(Request $req) {
		
		if($req->input('title')) {
			
			/*$this->validate($req, [
				'title' => 'required',
				'video_url' => 'required',
				]);
				*/
				$inputdata=array();
                $inputdata['title'] = $req->input('title');
                $inputdata['video_url'] = $req->input('video_url');
                $obj = Introduction_content::create($inputdata);
				
				$heading = $req->input('heading');
				$description = $req->input('description');
				
			if(is_array($heading) && count($heading)>0){
				for($i=0; $i<count($heading); $i++) {
					$inputdata=array();
					$inputdata['content_id'] = $obj->id;
					$inputdata['heading'] = $heading[$i];
					$inputdata['description'] = $description[$i];
					Introduction_desc::create($inputdata);
				}
			}	
			$mes ="Content added successfully.";
			return redirect()->route('admin.introduction-content')->with('flash_message', $mes);
			
		}
		$data['title'] = 'Introduction Content';
		$data['active_menu'] = 'introduction_content';
		return view('backend.introduction_content', $data);
	}

}
