<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\mobilead;
use App\Models\MobileAdsVehicleLicense;
use App\Models\VehicleMobileAds;
use App\Models\User;
use App\Models\UserAdmin;
use App\Models\AdminRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use PHPMailer\PHPMailer\PHPMailer;

class EditAdsController extends Controller   {


    public function deleteMobileAdsLicense($mobileId,  $mobileLicenseId) {

        $userId = Auth::user()->id;

        $getMobileAds = mobilead::where('id', $mobileId)->get();
        $getMobileAdsUser = (string) $getMobileAds[0]['user_id'];
        $count = MobileAdsVehicleLicense::where('mobilead_id', $mobileId)->count();

        if($userId == $getMobileAdsUser && $count > 1) {
            $mobileObj = mobilead::findorfail($mobileId);
            $mobileObj->mobileAdsVehicleLicense()->where('id', $mobileLicenseId)->delete();
            return response()->json(['success' => true, 'message' => 'Mobile License successfully deleted'], 200);
        } else {
            return response()->json(['success' => false, 'message' => 'Unable to delete mobile license'], 422);
        }

    }

    public function addMobileAdsLicense(Request $request, $mobileId) {

        $validate = Validator::make($request->all(), [
            'vehiclelicense' => 'required|string',
            'brandingtype' => 'required|string',
            'vehicletype' => 'required|string'
        ]);


        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }

        $mobileInput = $request->all();
        $mobileObj = mobilead::findorfail($mobileId);
        $vehicleLicense = new MobileAdsVehicleLicense();
        $vehicleLicense->vehicle_type = $mobileInput['vehicletype'];
        $vehicleLicense->vehicle_license = $mobileInput['vehiclelicense'];
        $vehicleLicense->branding_details = $mobileInput['brandingtype'];
        $response = $mobileObj->mobileAdsVehicleLicense()->save($vehicleLicense);
        return response()->json(['data' => $response], 200);
    }

    public function editMobileAdsLicense(Request $request, $mobileId) {

        $validate = Validator::make($request->all(), [
            'previousbrandingtype' => 'required|string',
            'previousvehicletype' => 'required|string',
            'brandingtype' => 'required|string',
            'vehicletype' => 'required|string'
        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }

        $mobileInput = $request->all();
        $mobileObj = mobilead::findorfail($mobileId);
        $response = $mobileObj->mobileAdsVehicleLicense()->where('branding_details', $mobileInput['previousbrandingtype'])
            ->where('vehicle_type', $mobileInput['previousvehicletype'])
            ->update(['branding_details' => $mobileInput['brandingtype'], 'vehicle_type' => $mobileInput['vehicletype']  ]);
        return response()->json(['data' => $response], 200);
    }

    public function updateImageMontageMobile(Request $request, $mobileId) {

        $validate = Validator::make($request->all(), [

            'montage' => 'present|array',
            'montage.mobileimage.*.mobilemontages' => 'required|array'
        ]);


        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }

        $mobileInput = $request->all();
        $count = count($mobileInput['montage']['mobilesMontage'])-1;

        $response = "";
        for ($i=0;$i<=$count;$i++) {
            $mobileObj = mobilead::findorfail($mobileId);
            $vehicleApplication = new VehicleMobileAds();
            $image64String = $mobileInput['montage']['mobilesMontage'][$i];
            $vehicleApplication->image_montage = $this->imageNamingSaving($image64String);
            $response = $mobileObj->vehicleMobile()->save($vehicleApplication);
        }
        return response()->json(['data' => $response], 200);
    }

    public function deleteMobileAdsLicenceAdmin($mobileId,  $mobileLicenseId) {

        if (Auth::user()->admin_role_id == 10 || Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3) {

            $getMobileAds = mobilead::where('id', $mobileId)->get();
            $count = MobileAdsVehicleLicense::where('mobilead_id', $mobileId)->count();
            if($count > 1) {
                $mobileObj = mobilead::findorfail($mobileId);
                $mobileObj->mobileAdsVehicleLicense()->where('id', $mobileLicenseId)->delete();
                return response()->json(['success' => true, 'message' => 'Mobile License successfully deleted'], 200);
            } else {
                return  response()->json(['success' => false, 'message' => 'Unable to delete the last mobile license'], 422);
            }
        } else {
            return response()->json(['success' => false, 'message' => 'Unable to delete mobile license'], 422);
        }
    }

    public function submitEditMobile($mobileId) {

        $updateStatus = mobilead::where('id', $mobileId)->update(['status' => 'pending', 'hod_permit_status' => null, 'legal_status' => null,
            'final_status' => null]);
        $response = mobilead::where('id', $mobileId)->get();
        return response()->json(['data' => $response], 200);
    }

    public function editBrandingName(Request $request, $mobileId) {

        $validate = Validator::make($request->all(), [
            'brandname' => 'required|string'
        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }
        $updateInput = $request->all();
        $mobileUpdate = mobilead::where('id', $mobileId)->update(['brand_name' => $updateInput['brandname'] ]);
        return  response()->json(['data' => $mobileUpdate], 200);
    }

    protected function  imageNamingSaving($base64Image) {
        $image = explode('base64,',$base64Image);
        $image = end($image);
        $image = str_replace(' ', '+', $image);
        //$filename =
        $uniqueid = uniqid();
        $file =  "/images/" . $uniqueid . '.png';

        Storage::disk('public')->put($file,base64_decode($image));

        $sourcePath = storage_path('app/public' . $file); // Get the source path in the storage directory
        $destinationPath = public_path('images/' . $uniqueid . '.png'); // Define the destination path in the public directory

        // Move the file from the storage directory to the public directory
        File::move($sourcePath, $destinationPath);

        $url = env('APP_URL').'/public'.$file;
        return $url;
    }
    
    public function adminEditUser(Request $request, $userid)  {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'business_name' => 'required|string|max:255',
            'phone_number' => 'required|string|min:11',
            'email' => 'required|string|email|max:255'
        ]);

        if($validator->fails()) {

            return response()->json(['errors' => $validator->errors()->all()], 422);
        }

        
        $request['email'] = Str::lower($request['email']);
        $editData = [
            'first_name' => $request['first_name'],
            'last_name' => $request['last_name'],
            'business_name' => $request['business_name'],
            'phone_number' => $request['phone_number'],
            'email' => $request['email'],
        ];
        
        $editUser = User::where('id', $userid)->update($editData);

        return response()->json(["success" => true, "message" => "updated successfully","data" => $editUser], 200);
    }
    
    public function editUserPassword(Request $request)  {
        $validator = Validator::make($request->all(), [
            'oldpassword' => 'required|min:8',
            'password' => 'required|min:8'
        ]);

        if($validator->fails()) {

            return response()->json(['errors' => $validator->errors()->all()], 422);
        }
        
        $userid = Auth::user()->id;
        $user = User::where('id', $userid)->first();
        if(Hash::check($request->oldpassword, $user->password)){
            $request['password' ]  = Hash::make($request['password']);
            $editData = [
                'password' => $request['password'],
            ];
            
            $editUser = User::where('id', $userid)->update($editData);
    
            return response()->json(["success" => true, "message" => "password updated successfully"], 200);  
        }else{
            return response()->json(["success" => false, 'errors' => "old password doesn't match"], 422);
        }
        
    }
    
    public function editAdminUser(Request $request, $adminid) {
        $validate = Validator::make($request->all(), [
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'email' => 'required|email',
            'phone_number' => 'required||min:11',
            'admin_role' => 'required|string',
            'line_manager' => 'required|numeric',
            'lga' => 'nullable|string',
            'zone' => 'nullable|string',
            'zone2' => 'nullable|string',
            'department' => 'nullable|string'
        ]);


        if ($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }

        $adminInput = $request->all();
        $adminrole = $adminInput['admin_role'];
        $adminrole = Str::upper($adminrole);
        $admin = AdminRole::where('role', $adminrole)->first();
        try {
            $editData = [
                'first_name' => $adminInput['first_name'],
                'last_name' => $adminInput['last_name'],
                'email' => $adminInput['email'],
                'phone_number' => $adminInput['phone_number'],
                'line_manager' => (string)$adminInput['line_manager'],
                'lga' => $adminInput['lga'],
                'zone' => $adminInput['zone'],
                'zone2' => $adminInput['zone2'],
                'department' => $adminInput['department'],
                'admin_role_id' => $admin->id,
            ];
            
            $editUser = UserAdmin::where('id', $adminid)->update($editData);
            
            return response()->json(["success" => true, 'message' => 'Admin Updated successfully'], 200);
            
        } catch (Illuminate\Database\QueryException  $ex) {
            $errorCode = $ex->errorInfo[1];
            
                Log::error("Duplicate entry  error: " .$ex->getMessage());
                return response()->json(["success" => false, 'error' =>  $ex->getMessage()], 500);

            
        }
    }
    
    public function checkEmailAdmin(Request $request) {

        $user = UserAdmin::where('email', $request->email)->first();

        if($user === null) {
            return response()->json(["success" => false, 'error' => 'Email does not exist!'], 422);
        } else {
            $verifyCode = $this->generateEmailToken();
            $this->composeEmail('OTP', $verifyCode, $user->email);
            UserAdmin::where('id', $user->id)->update(['verify_code' => $verifyCode]);
            return response()->json(["success" => true, 'message' => 'Email / phonenumber exists and OTP sent', 'userId' => $user->id], 200);
        }
    }
    
    public function checkTokenUpdate(Request $request) {

            // $userid = Auth::user()->id;
            $userid = $request['userid'];
            // var_dump($userid); die();
            $user = UserAdmin::where('id', $userid)->first();

            $usertoken = $user->verify_code;

            if($usertoken == $request['otp']) {
                return response()->json(["success" => true, 'message' => 'Valid OTP!'], 200);

            } else {
                return response()->json(["success" => false, 'error' => 'Invalid OTP!'], 422);
            }
    }
    
    public function changeAdminPassword(Request $request) {

        if($request->isMethod('PATCH')) {

            $validate = Validator::make($request->all(), [
                'userid' => 'required|integer',
                'otp' => 'required|integer',
                'password' => 'required|min:8'
            ]);

            if($validate->fails()) {
                return response()->json(['error' => $validate->errors()->all()], 422);
            }

            $user = $request['userid'];
            //var_dump($user); die();
            $request['password' ]  = Hash::make($request['password']);
            UserAdmin::where('id', $user)->where('verify_code', $request['otp'])->update(['password' => $request['password'], 'verify_code' => '']);
            return response()->json(["success" => true, 'message' => 'Password successfully changed'], 200);
        }
    }
    
    public function generateEmailToken() {
        $emailToken = rand(100000, 999999);
        return $emailToken;
    }
    
    public function composeEmail($subject, $body,  $userEmail){
        
        require base_path('vendor/autoload.php');

        $mail = new PHPMailer(true);
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'smtp-relay.brevo.com'; //ssl://smtp.gmail.com
        $mail->SMTPAuth = true;
        $mail->Username = 'macdonnad@gmail.com';
        $mail->Password = 'xsmtpsib-93267ec9551960673300f309d7edd9a807648eb7aac5b10b6f80f2e106c7f010-dMSfPhNXDW84pqvY';
        // $mail->SMTPSecure = 'ssl';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->setFrom('NoReply@lasaa.lg.gov.ng', 'Lasaa');
        $mail->addAddress($userEmail);
        $mail->addReplyTo('NoReply@lasaa.lg.gov.ng', 'Lasaa');

        $mail->isHTML(true);

        $mail->Subject = $subject;
        $mail->Body = "Verification code: " .$body;
        $mail->send();

    }
}
