<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CarWashOwner;
use App\Models\User;
use App\Models\UserPermission;
use App\Models\Permission;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Password;
use Config;
use Hash;
use Auth;
use Session;

class CwoRegistrationController extends Controller
{
    public function __construct(){
    }


    public function index(){
    }

    public function appregistration(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'cwo_name' => 'required',
                'cwo_company' => 'required',
                'cwo_email' => 'required|email|unique:cwo_master,cwo_email',
                'cwo_phone' => 'required',
                'address' => 'required',
                'password' => [
                    'required',
                    // 'confirmed',
                    // 'string',
                    // 'min:8',             // must be at least 8 characters in length
                    // 'regex:/[a-z]/',      // must contain at least one lowercase letter
                    // 'regex:/[A-Z]/',      // must contain at least one uppercase letter
                    // 'regex:/[0-9]/',      // must contain at least one digit
                    // 'regex:/[!@#$%^&*()]/', // must contain a special character
                ],
            ],[
                'cwo_email.unique' => 'This email already exists.',
                // 'password.confirmed' => 'The password and confirm password field should be same.'
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }
        // exit;

        $cwo_name = $request->input('cwo_name');
        $cwo_company = $request->input('cwo_company');
        $cwo_email = $request->input('cwo_email');
        $cwo_isd = $request->input('cwo_isd');
        $cwo_phone = $request->input('cwo_phone');
        $password = Hash::make($request->input('password'));
        $allow_prebooking = $request->input('allow_prebooking');
        if($allow_prebooking == ''){
            $allow_prebooking = 0;    
        }
        // echo $allow_prebooking;exit;
        $user_name = $request->input('cwo_name');
        $address = $request->input('address');
        // $currency_id = $request->input('currency_id');
        $dt = Carbon::now(); 
        $account_no = generateUniqueNumberCWO();
        $is_paid = 1;
        // echo $account_no;exit;
        // echo strtok($cwo_isd, ' ');exit;

        if($address != ''){
            $addr = getLatLongFromAddress($address);
            // print_r($addr);exit;
            $lat = $addr['lat'];
            $long = $addr['long'];
        } else {
            $lat = '';
            $long = '';
        }

        $cwo_logo = '';
        if ($request->hasFile('cwo_logo')) {
            $cwo_logo = time() . '.' . $request->file('cwo_logo')->extension();
            $path = $request->file('cwo_logo')->move(public_path('images/cwo/'), $cwo_logo);
        }

        /*insert into cwo_master table starts*/
        $data = CarWashOwner::create([
            'cwo_name'=> $cwo_name,
            'cwo_company'=> $cwo_company,
            'cwo_email'=> $cwo_email,
            'cwo_isd'=> strtok($cwo_isd, ' '),
            'cwo_phone'=> $cwo_phone,
            'allow_prebooking'=> $allow_prebooking,
            'is_paid'=> $is_paid,
            'cwo_logo'=> $cwo_logo,
            'account_no'=> $account_no,
            'address'=> $address,
            'currency_id'=> 95,
            'lat'=> $lat,
            'long'=> $long,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        /*insert into cwo_master table ends*/

        /*insert into users table starts*/
        $cwo_id = $data->id;
        if($cwo_name == ''){
            $cwo_name = $cwo_company;
        }
        $dataCwo = User::create([
            'name'=> $user_name,
            'email'=> $cwo_email,
            'password'=> $password,
            'user_type'=> 2,
            'is_active'=> 1,
            'is_admin'=> 1,
            'isd_code'=> strtok($cwo_isd, ' '),
            'phone'=> $cwo_phone,
            'cwo_id'=> $cwo_id,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        /*insert into users table ends*/

        /*insert into user_permissions table starts*/
        $getAllPermissions = Permission::where('is_active', 1)->get();
        if($getAllPermissions != '') {
            foreach ($getAllPermissions as $p) {
                UserPermission::create([
                    'user_id' =>  $dataCwo->id,
                    'permission_id' => $p->id,
                    'created_at' => $dt->toDayDateTimeString(),
                    'updated_at' => $dt->toDayDateTimeString()
                ]);
            }
        }
        /*insert into user_permissions table ends*/

        $time = strtotime(date("Y-m-d"));
        $trial_expiry_date = date("Y-m-d", strtotime("+7 day", $time));
        $data->update([
            'free_trial'=> 1,
            'trial_expiry_date'=> $trial_expiry_date,
            'start_date'=> date('Y-m-d'),
            'end_date'=> $trial_expiry_date,
            'updated_at'=>$dt->toDayDateTimeString()
            ]);
        // exit;    
        /*send mail starts*/
        $recipient_name = $cwo_name;
        // $recipient_email = 'tamashree@karmicksolutions.com';
        $recipient_email = $cwo_email;
        // $message_body = 'test body';
        $subject = 'Autoclick - Registration Successful'; 
        $message_body = '<html>
        <head>
        <title>Welcome to Autoclick</title>
        </head>
        <body>
            <p>Dear ' . $cwo_name . '</p>
            <p>Thank you for signing up to become a partner, welcome to the smart revolution of running your carwash business transactions better. Enjoy the free 7 days trial and thereafter you pay ZAR250 per month.</p>
            <p>Your username, password and account number are as follows.</p>
            <p>Username: '.$cwo_email.' , Password: '.$request->input('password').' and Account No.: ' . $account_no .'</p>
            <p></p>
            <p><strong>Next Steps</strong> is to login to the partners portal to add your carwash services and prices. After that you must download the app on Google Play</p>
            <p></p>
            <p><strong>Link to login and add your services:</strong> <a href="https://autoclickpartnersapp.com/">https://autoclickpartnersapp.com/</a></p>
            <p><strong>Download Android App link:</strong> <a href="https://play.google.com/store/apps/details?id=com.autoclickcarwash.bo">https://play.google.com/store/apps/details?id=com.autoclickcarwash.bo</a></p>
            <p>You can search the app on Google Play by typing Autoclick Carwash Business</p>
            <p></p>
            <p>Read more about what the app can do for your business by visiting our website <a href="https://autoclickcarwashapp.com/">www.autoclickcarwashapp.com</a></p>
            <p></p>
            <p><strong><a href="'. route('login') .'">Click here to login</a></strong> and complete your business profile</p>
            <p>Warm Regards</p>
            <p>Autoclick | +27 71 641 8942 </p>
            <p><a href="mailto: support@autoclick.co.za">support@autoclick.co.za</a> | <a href="https://autoclickcarwashapp.com/">www.autoclickcarwashapp.com</a></p>
        </body>
    </html>';              
        $email = sendMail(array($recipient_name, $recipient_email), $message_body, $subject);
        // print_r($email);exit;
        /*send mail ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Your registration has been successful. Enjoy the free 7 days trial. Contact administrator for further assistance.',
            'cwo_id' => $cwo_id,
            'cwo_account_no' => $account_no,
            'user_id' => $dataCwo->id
        ]);

    }

}
