<?php

namespace App\Controllers\Authentication;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Common_M;

use App\Models\Registration_M;

class Registration_C extends BaseController
{
    public function __construct()
    {
        $this->common_obj = new Common_M();
    }

    public function index()
    {
        return view("authentication/registration");
    }
    public function signup_submit()
    {
            $name = $this->request->getVar("name");
            $email = $this->request->getVar("email");
            $mobile = $this->request->getVar("mobile");
            $password = $this->request->getVar("password");
            $clinic_name = $this->request->getVar("clinic_name");
            $user_id = $this->generate_unique_user_id();

            $master_clinic_data=array(
                "clinic_name"=>$clinic_name,
                "clinic_contact_person"=>$name,
                "clinic_mobile_number"=>$mobile,
                "clinic_email_id"=>$email,
            );
            $insert = $this->common_obj->data_insert('master_clinics',$master_clinic_data);

            $model = new Registration_M();
            $ins_data = [
                "user_id" => $user_id,
                "master_id" => $insert,
                "password" => md5($password),
                "user_type" => 0
            ];
            $insert = $model->register($ins_data);

            $email = \Config\Services::email();
            $email->setFrom('support@gd.com', 'GD - Support Team');
            $email->setTo('sourav.daas98@gmail.com');
            //$email->setCC('sayakmukherjee87@gmail.com');
            
            $email->setSubject('New Registration');       
            $message = "Dear $name,<br/><br/>
            Thank you for registering. Your login credentials are:<br/><br/>
            User Id : $user_id<br/>
            Password: $password<br/>";
        
            $email->setMessage($message);
            $email->setMailType('html');
            $email->send();
            $response=array(
                "status"=>1,
                "code"=>"011",
                "message"=>"Registration Successfull"
            );
            echo json_encode($response);
        
    }
    public function generate_unique_user_id()
    {
        $user_id = rand(100000, 999999);
        $model = new Registration_M();
        while ($model->is_user_id_exists($user_id)) {
            $user_id = rand(100000, 999999);
        }

        return $user_id;
    }
}
