<?php
namespace App\Http\Controllers;

use App\Models\Contact;
use App\Models\User;
use App\Models\Listingverification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use App\Mail\ContactUsEmail;
use App\Mail\VerificationLawyerEmail;
use App\Mail\VerificationUserEmail;
use App\Mail\NotificationNewUserEmail;
use App\Mail\NotificationVerificationEmail;
use App\Mail\ReferEmail;


class FormController extends Controller
{   
    // Store Contact Form data
    public function contactFormStore(Request $request)
    {
	/*
        //  Store data in database
        $store = Contact::create([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'contact' => $request->contact,
            'zip' => $request->zip,
            'summary' => $request->summary,
        ]);
	*/
        if($request){
            if ($request->con_emails != "") {
                Mail::to($request->con_emails)->send(new ContactUsEmail($request));
                return json_encode(array('success' => 'Thank you. Form submitted successfully.'));
            } else {
                return json_encode(array('error' => 'Something Went Wrong'));
            }
        }
    }

    // STORE LAWYER LISTING
    public function lawyer_register(Request $request)
    {   
        $l_role = DB::select('SELECT * FROM `roles` WHERE `name`="Lawyer"');
        $e_user = DB::table('users')->where('email',$request->email)->first();

        if(!$e_user){

            $ref_id = "";
            if(Session::has('ref_lid')){
                $ref_id = Session::get('ref_lid');
            }

            //  add user in database
            $id = DB::table('users')->insertGetId([
                'name' => ucwords($request->first_name.' '.$request->last_name),
                'email' => $request->email,
                'phone' => $request->phone,
                'email_verification_token' => Str::random(60),
                'referral_id' => $ref_id,
                'password' => Hash::make($request->password),
                'created_at' => date('Y-m-d H:i:s'),
                'listing_claim_id' => $request->list_id,
            ]);

            if($id){
                $lr_id = DB::table('model_has_roles')->insertGetId([
                    'role_id' => $l_role[0]->id,
                    'model_type' => 'App\Models\User',
                    'model_id' => $id,
                ]);

                $user = User::find($id);
                Mail::to($request->email)->send(new VerificationLawyerEmail($user));
                $admin_email = 'notification@legal.com';
                Mail::to($admin_email)->send(new NotificationNewUserEmail($user));
                return json_encode(array('e_code'=> 0,'success'=> 'You are now registered as an attorney. Check your email to verify your account and manage your profile.','error'=>''));
            }
        }else{
            return json_encode(array('e_code'=>'e_exists','error'=> 'Email already exists. <a href="#" id="resend_verification">Resend Verification</a>'));
        }
    }

    // STORE SIMPLE USER
    public function user_register(Request $request){
        $u_role = DB::select('SELECT * FROM `roles` WHERE `name`="Subscriber"');
        $e_user = DB::table('users')->where('email',$request->user_email)->first();

        if(!$e_user){

            //  add user in database
            $id = DB::table('users')->insertGetId([
                'name' => ucwords($request->user_name),
                'email' => $request->user_email,
                'password' => Hash::make($request->user_password),
                'email_verification_token' => Str::random(60),
                'created_at' => date('Y-m-d H:i:s'),
            ]);

            if($id){
                $lr_id = DB::table('model_has_roles')->insertGetId([
                    'role_id' => $u_role[0]->id,
                    'model_type' => 'App\Models\User',
                    'model_id' => $id,
                ]);
                $user = User::find($id);
                Mail::to($request->user_email)->send(new VerificationUserEmail($user));
                return json_encode(array('e_code'=> 0,'success'=> 'You are now registered as user. Check your email to verify your account and manage your profile.','error'=>''));
            }
        }else{
            return json_encode(array('e_code'=>'e_exists','error'=> 'Email already exists. <a href="#" id="resend_verification">Resend Verification</a>'));
        }
    }

    // UPDATE USER OR LAWYER
    public function all_user_update(Request $request){
        if($request->user_type == "subscriber"){
            $c_user = DB::table('users')->where('id', '=', $request->c_user_id)->first();
            $e_user = DB::table('users')->where('email', '=', $request->user_email)->where('id', '!=', $request->c_user_id)->first();

            if(!$e_user){
                if($request->user_password != ""){
                    $pass = Hash::make($request->user_password);
                }else{
                    $pass = $c_user->password;
                }

                // update user in database
                $gen_update = DB::table('users')->where('id', $request->c_user_id)
                ->update([
                    'name' => ucwords($request->user_name),
                    'email' => $request->user_email,
                    'password' => $pass,
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);

                if($gen_update){
                    return json_encode(array('e_code'=> 0,'success'=> 'User Updated successfully.','error'=>''));
                }
            }else{
                return json_encode(array('e_code'=>'e_exists','error'=> 'Email already exists'));
            }
        }

        if($request->user_type == "lawyer_personal"){
            $c_user = DB::table('users')->where('id', '=', $request->c_user_id)->first();
            $e_user = DB::table('users')->where('email', '=', $request->personal_info['l_email'])->where('id', '!=', $request->c_user_id)->first();

            if(!$e_user){

                // update user in database
                // $gen_update = DB::table('users')->where('id', $request->c_user_id)
                // ->update([
                //     'name' => $request->personal_info['l_fname'].' '.$request->personal_info['l_middle_name'].' '.$request->personal_info['l_last_name'],
                //     'email' => $request->personal_info['l_email'],
                //     'phone' => $request->personal_info['l_phone'],
                //     'updated_at' => date('Y-m-d H:i:s'),
                // ]);

                // update listing in database
                $e_list = DB::table('listings')->where('user_id', '=', $request->c_user_id)->first();
                if($e_list){
                    $e_list_id = $e_list->id;
                    $list_update = DB::table('listings')->where('id', $e_list_id)
                    ->update([
                        'picture' => $request->personal_info['user_image'],
                        'first_name' => ucwords($request->personal_info['l_fname']),
                        'middle_name' => ucwords($request->personal_info['l_middle_name']),
                        'last_name' => ucwords($request->personal_info['l_last_name']),
                        'suffix' => $request->personal_info['l_sufffix'],
                        'firm_id' => $request->personal_info['l_firms'],
                        'phone' => $request->personal_info['l_phone'],
                        'fax' => $request->personal_info['l_fax'],
                        'url' => $request->personal_info['l_website'],
                        'email' => $request->personal_info['l_email'],
                        'user_id' => $request->c_user_id,
                        // 'experience_years' => $request->personal_info['l_experience'],
                        'description' => $request->biography['description'],
                        'prefix' => $request->personal_info['l_prefix'],
                        'languages' => '',
                        'updated_at' => date('Y-m-d H:i:s'),
                    ]);
                }else{
                    $id = DB::table('listings')->insertGetId([
                        'picture' => $request->personal_info['user_image'],
                        'first_name' => ucwords($request->personal_info['l_fname']),
                        'middle_name' => ucwords($request->personal_info['l_middle_name']),
                        'last_name' => ucwords($request->personal_info['l_last_name']),
                        'suffix' => $request->personal_info['l_sufffix'],
                        'firm_id' => $request->personal_info['l_firms'],
                        'phone' => $request->personal_info['l_phone'],
                        'fax' => $request->personal_info['l_fax'],
                        'url' => $request->personal_info['l_website'],
                        'email' => $request->personal_info['l_email'],
                        'user_id' => $request->c_user_id,
                        // 'experience_years' => $request->personal_info['l_experience'],
                        'description' => $request->biography['description'],
                        'prefix' => $request->personal_info['l_prefix'],
                        'languages' => '',
                        'admin_verified' => '1',
                        'created_at' => date('Y-m-d H:i:s'),
                    ]);

                    $e_list_id = $id;
                }

                // PRACTICE AREA UPDATE
                $p_area = $request->personal_info['l_practice_area'];
                $e_parea = DB::select('SELECT * FROM `listing_practice_area` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_parea)){
                    foreach($e_parea as $ep){
                        DB::table('listing_practice_area')->where('id', $ep->id)->delete();
                    }
                }

                if(!empty($p_area)){
                    foreach($p_area as $pa){
                        if($pa != ""){
                            $id = DB::table('listing_practice_area')->insertGetId([
                                'listing_id' => $e_list_id,
                                'practice_area_id' => $pa,
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                // FEES UPDATE
                $fees = $request->fees_info;
                $e_fees = DB::select('SELECT * FROM `listing_fees` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_fees)){
                    foreach($e_fees as $ef){
                        DB::table('listing_fees')->where('id', $ef->id)->delete();
                    }
                }

                if(!empty($fees)){
                    foreach($fees as $fee){
                        if($fee['l_fees'] != ""){
                            $id = DB::table('listing_fees')->insertGetId([
                                'listing_id' => $e_list_id,
                                'fee_id' => $fee['l_fees'],
                                'description' => $fee['l_fee_description'],
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                // Jurisdictions Admitted to Practice UPDATE
                $jap = $request->jurisdictions;
                $e_jap = DB::select('SELECT * FROM `listing_jurisdictions` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_jap)){
                    foreach($e_jap as $ef){
                        DB::table('listing_jurisdictions')->where('id', $ef->id)->delete();
                    }
                }

                if(!empty($jap)){
                    foreach($jap as $j){
                        if($j['l_court_dist'] != ""){
                            $id = DB::table('listing_jurisdictions')->insertGetId([
                                'listing_id' => $e_list_id,
                                // 'district_id' => $j['l_court_dist'],
                                'name' => $j['l_court_dist'],
                                'since' => $j['l_court_since'],
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                // Address UPDATE
                $address = $request->addresses;
                $e_address = DB::select('SELECT * FROM `listing_address` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_address)){
                    foreach($e_address as $eaddr){
                        DB::table('listing_address')->where('id', $eaddr->id)->delete();
                    }
                }

                if(!empty($address)){
                    foreach($address as $addr){
                        if($addr['l_address_city'] != "" && $addr['l_address_state'] != ""){
                            $primary = 0;
                            if($addr['l_address_primary'] == "yes"){
                                $primary = 1;
                            }

                            $id = DB::table('listing_address')->insertGetId([
                                'listing_id' => $e_list_id,
                                'label' => $addr['l_address_label'],
                                'full_address' => $addr['l_address_full'],
                                'county' => $addr['l_address_county'],
                                'city' => $addr['l_address_city'],
                                'state' => $addr['l_address_state'],
                                'country' => $addr['l_address_county'],
                                'zipcode' => $addr['l_address_zip'],
                                'primary' =>  $primary,
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                // Educational Experiences UPDATE
                $edu_exp = $request->educational_experiences;
                $e_eduexp = DB::select('SELECT * FROM `listing_educations` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_eduexp)){
                    foreach($e_eduexp as $e_ed){
                        DB::table('listing_educations')->where('id', $e_ed->id)->delete();
                    }
                }

                if(!empty($edu_exp)){
                    foreach($edu_exp as $edex){
                        if($edex['l_edu_exp_activities'] != "" && $edex['l_edu_exp_honors'] != "" && $edex['l_edu_exp_institute'] != "" && $edex['l_edu_exp_title'] != ""){
                            $id = DB::table('listing_educations')->insertGetId([
                                'listing_id' => $e_list_id,
                                'institution' => $edex['l_edu_exp_institute'],
                                'title' => $edex['l_edu_exp_title'],
                                'honors' => $edex['l_edu_exp_honors'],
                                'activities' => $edex['l_edu_exp_activities'],
                                'year_started' => $edex['l_edu_exp_year_start'],
                                'year_ended' => $edex['l_edu_exp_year_end'],
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                // Professional Associations UPDATE
                $pro_asso = $request->professional_associations;
                $e_pro_asso = DB::select('SELECT * FROM `listing_professional_associations` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_pro_asso)){
                    foreach($e_pro_asso as $e_paso){
                        DB::table('listing_professional_associations')->where('id', $e_paso->id)->delete();
                    }
                }

                if(!empty($pro_asso)){
                    foreach($pro_asso as $proes){
                        if($proes['l_pro_asso_institute'] != "" && $proes['l_pro_asso_position'] != "" && $proes['l_pro_asso_year_end'] != "" && $proes['l_pro_asso_year_start'] != ""){
                            $id = DB::table('listing_professional_associations')->insertGetId([
                                'listing_id' => $e_list_id,
                                'position' => $proes['l_pro_asso_position'],
                                'institution' => $proes['l_pro_asso_institute'],
                                'year_started' => $proes['l_pro_asso_year_start'],
                                'year_ended' => $proes['l_pro_asso_year_end'],
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                // Publications UPDATE
                $publi = $request->publications;
                $e_publication = DB::select('SELECT * FROM `listing_publications` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_publication)){
                    foreach($e_publication as $e_pub){
                        DB::table('listing_publications')->where('id', $e_pub->id)->delete();
                    }
                }

                if(!empty($publi)){
                    foreach($publi as $publ){
                        if($publ['l_pub_title'] != "" && $publ['l_pub_link'] != "" && $publ['l_pub_medium'] != "" && $publ['l_pub_date'] != ""){
                            $id = DB::table('listing_publications')->insertGetId([
                                'listing_id' => $e_list_id,
                                'title' => $publ['l_pub_title'],
                                'url' => $publ['l_pub_link'],
                                'medium' => $publ['l_pub_medium'],
                                'date_published' => $publ['l_pub_date'],
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                // Website & Blog Entries UPDATE
                $webs = $request->websites;
                $e_links = DB::select('SELECT * FROM `listing_links` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_links)){
                    foreach($e_links as $e_link){
                        DB::table('listing_links')->where('id', $e_link->id)->delete();
                    }
                }

                if(!empty($webs)){
                    foreach($webs as $web){
                        if($web['l_web_title'] != "" && $web['l_web_link'] != "" && $web['l_web_date'] != "" && $web['l_web_type'] != ""){
                            $id = DB::table('listing_links')->insertGetId([
                                'listing_id' => $e_list_id,
                                'type' => $web['l_web_type'],
                                'title' => $web['l_web_title'],
                                'url' => $web['l_web_link'],
                                'date_published' => $web['l_web_date'],
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                // Social Links UPDATE
                $socials = $request->social;
                $e_links = DB::select('SELECT * FROM `listing_social_networks` WHERE `listing_id`="'.$e_list_id.'"');

                if(!empty($e_links)){
                    foreach($e_links as $e_link){
                        DB::table('listing_social_networks')->where('id', $e_link->id)->delete();
                    }
                }

                if(!empty($socials)){
                    foreach($socials as $social){
                        if($social['l_social_type'] != "" && $social['l_social_link'] != ""){
                            $id = DB::table('listing_social_networks')->insertGetId([
                                'listing_id' => $e_list_id,
                                'type' => $social['l_social_type'],
                                'url' => $social['l_social_link'],
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }
                    }
                }

                return json_encode(array('e_code'=> 0,'success'=> 'User Updated successfully.','error'=>''));
            }else{
                return json_encode(array('e_code'=>'e_exists','error'=> 'Email already exists'));
            }
        }

        if($request->user_type == "lawyer_company"){
            $e_firm = DB::table('firms')->where('name', '=', $request->company_info['company_name'])->where('email', '=', $request->company_info['company_email'])->first();

            if(!$e_firm){
                // add company in database
                $id = DB::table('firms')->insertGetId([
                    'name' => $request->company_info['company_name'],
                    'phone' => $request->company_info['company_phone'],
                    'fax' => $request->company_info['company_fax'],
                    'url' => $request->company_info['company_url'],
                    'description' => $request->company_info['company_description'],
                    'email' => $request->company_info['company_email'],
                    'address1' => $request->company_info['company_addr_1'],
                    'address2' => $request->company_info['company_addr_2'],
                    'city' => $request->company_info['company_city'],
                    'county' => $request->company_info['company_county'],
                    'state' => $request->company_info['company_state'],
                    'country' => $request->company_info['company_country'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);

                return json_encode(array('e_code'=> 0,'success'=> 'Company Added successfully.','error'=>''));
            }else{
                return json_encode(array('e_code'=>'f_exists','error'=> 'Company already exists'));
            }
        }
    }

    // VERIFY DOCS
    public function verify_doc(Request $request){
        $u_id = $request->c_user_id;
        $db_arr = array();

        if(!empty($_FILES)){
            if($u_id){
                $path = 'uploads/verification-documents/lawyers/' . $u_id . '/';
                if (\File::exists($path)) \File::deleteDirectory($path);

                foreach($_FILES as $fk=>$files){
                    $file = $request->file($fk);
                    $filename = time() . '_' . $file->getClientOriginalName();

                    $location = $path.$fk.'/';
                    $file->move($location, $filename);

                    $db_arr[$fk] = $filename;
                }

                // ADD IN DB
                $e_vdoc = DB::table('user_verification_documents')->where('user_id', '=', $u_id)->first();

                if(!$e_vdoc){
                    // add company in database
                    $id = DB::table('user_verification_documents')->insertGetId([
                        'user_id' => $u_id,
                        'documents' => json_encode($db_arr),
                        'listing_id' => 0,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ]);
                }else{
                    $list_update = DB::table('user_verification_documents')->where('user_id', $u_id)
                    ->update([
                        'user_id' => $u_id,
                        'listing_id' => 0,
                        'documents' => json_encode($db_arr),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ]);
                }
                $admin_email = 'notification@legal.com';
                $user = User::find($u_id);
                $entry = Listingverification::where('user_id', $u_id)->first();
                Mail::to($admin_email)->send(new NotificationVerificationEmail($user, $entry));

                return json_encode(array('e_code'=> 0,'success'=> 'Document uploaded successfully.','error'=>''));

            }else{
                return json_encode(array('e_code'=>'user_id-wrong','error'=> 'Something Went Wrong'));
            }
        }else{
            return json_encode(array('e_code'=>'no_files-wrong','error'=> 'Something Went Wrong'));
        }
    }


    // LOGIN
    public function login(Request $request){
        $email = $request->email;
        $password = $request->password;

        $user = DB::table('users')->where('email', $email)->first();

        if (!$user) {
            return json_encode(array('success'=>false,'error' => 'Login Fail, Please double-check your email','e_code' => 'e'));
        }
        if (!Hash::check($password, $user->password)) {
            return json_encode(array('success'=>false, 'error' => 'Login Fail, Please double-check your password','e_code' => 'p'));
        }
        if($user->email_verified_at == "" || $user->email_verified_at == null){
            return json_encode(array('success'=>false, 'error' => 'Login Fail, Please verify your email address. <a href="#" id="resend_verification">Resend Verification</a>','e_code' => 'e'));
        }
        
        Session::put('f_user_login', 1);
        Session::put('user_id', $user->id);
        Session::put('username', $user->name);
        return json_encode(array('success'=>true,'error' => '', 'message'=>'Login success', 'data' => $user));
    }

    // RESEND EMAIL VERIFICATION
    public function resend_email_verification(Request $request)
    {
        $email = $request->email;
        $user = DB::table('users')->where('email', $email)->first();

        if ($user) {
            $user_r_id = DB::table('model_has_roles')->where('model_id', $user->id)->first();

            if($user_r_id){
                $user_r = DB::table('roles')->where('id', $user_r_id->role_id)->first();
                if($user_r){
                    $user_role = $user_r->name;
                    $user = User::find($user->id);

                    if($user_role == "Lawyer"){
                        Mail::to($email)->send(new VerificationLawyerEmail($user));
                    }else{
                        Mail::to($email)->send(new VerificationUserEmail($user));
                    }
                    return json_encode(array('success'=>true ,'error' => '' ,'message' => 'Verification email sent...'));

                }else{
                    return json_encode(array('success'=>false,'error' => 'Something went wrong','e_code' => 'e'));
                }
            }else{
                return json_encode(array('success'=>false,'error' => 'Something went wrong','e_code' => 'e'));
            }
        }else{
            return json_encode(array('success'=>false,'error' => 'Something went wrong','e_code' => 'e'));
        }
    }

    // REFERRAL
    public function l_referral(Request $request){
        //  add user in database
        // $id = DB::table('user_referral')->insertGetId([
        //     'user_id' => $request->cur_u_id,
        //     'email' => $request->ref_email,
        //     'referral_url' => $request->referral_url,
        //     'created_at' => date('Y-m-d H:i:s'),
        //     'updated_at' => date('Y-m-d H:i:s'),
        // ]);

        Mail::to($request->ref_email)->send(new ReferEmail($request));
        return json_encode(array('e_code'=> 0,'success'=> 'Thank you. Invitation Sent.','error'=>''));
    }
}
