<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require APPPATH . '/libraries/BaseController.php';

class Site extends BaseController
{

    public $isApproved;
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->model('login_model');
        $userId = $this->session->userdata('userId');
        if ($userId) {

            $userData = $this->user_model->getUserInfoById($userId);
            $approved = $userData->approved;
            $this->isApproved = $approved;
        }
    }

    public function searchUsers()
    {
        $myId = $this->session->userdata('userId');
        $searchTerm = $this->input->post('searchTerm');
        $userData = $this->user_model->searchUsers($searchTerm, $myId);
        echo (json_encode($userData));
    }

    public function index()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        redirect(base_url() . 'site/community');

        //        $this->loadViews("questions");
    }

    public function forgot()
    {
        $this->load->view("forgot");
    }

    public function doforgot()
    {
        $useremail = $this->input->post("email");
        $user = $this->user_model->getUserInfoByEmail($useremail);
        if (!$user) {
            $this->session->set_flashdata('error', "Invalid email address");
            redirect(base_url('site/forgot'));
        }
        $name = $user->name;
        $userId = (int)$user->id;

        if ($userId > 0) {
            $password = uniqid();
            $hashedPassword = getHashedPassword($password);
            $this->load->library('email');
            $config = array();

            $config['protocol'] = 'smtp';
            $config['smtp_host'] = 'ssl://mail.buzzwaretech.com';
            $config['smtp_user'] = 'testweb@buzzwaretech.com';
            $config['smtp_pass'] = ',j8Og2d1Ty1%';
            $config['smtp_port'] = 465;
            $config['mailtype'] = 'html';
            $config['charset'] = 'iso-8859-1';
            $config['wordwrap'] = 'TRUE';
            $config['newline'] = "\r\n";
            $this->email->initialize($config);
            $this->email->set_newline("\r\n");
            $from_email = "testweb@buzzwaretech.com";
            $this->email->from($from_email, 'Dentifyd');
            $this->email->to($useremail);
            $this->email->subject("New password from Dentifyd");
            $message = "Hi " . $name . "<br><br>Below is your temporary password from Dentifyd.Please change it as soon as possible.<br><br>Password: <b>" . $password . "</b><br><br>Dentifyd Team";
            $this->email->message($message);

            if ($this->email->send()) {
                $userData = array(
                    'password' => $hashedPassword
                );
                $this->user_model->editUser($userData, $userId);
                $this->session->set_flashdata('success', 'New password sent to your email address');
                redirect(base_url('login'));
            } else {
                $this->session->set_flashdata('error', "We are currently unable to handle this request");
                redirect(base_url('site/forgot'));
            }
        } else {
            $this->session->set_flashdata('error', "Invalid email address");
            redirect(base_url('site/forgot'));
        }
    }

    public function product($productId)
    {
        if (!$this->isAdmin()) {

            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        if (!$productId) {
            redirect('site/store');
        }
        $data['product'] = $this->user_model->getProductById($productId);
        $data['content'] = 'productdetail';



        $this->loadViews("productdetail", null, $data);
    }

    public function myorders()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }

        $data['myOrders'] = $this->user_model->getMyOrders($userId);
        $this->loadViews("myorders", null, $data);
    }

    function check_diff_multi($array1, $array2)
    {
        $result = array();
        foreach ($array1 as $key => $val) {
            if (isset($array2[$key])) {
                if (is_array($val) && $array2[$key]) {
                    $result[$key] = $this->check_diff_multi($val, $array2[$key]);
                }
            } else {
                $result[$key] = $val;
            }
        }

        return $result;
    }


    public function chat($otherUserId = null)
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }

        // $lastMessages = $this->user_model->getLastMessage(1, 5);


        $isUserSubscribed = $this->user_model->isUserSubscribed($userId);
        if (!$isUserSubscribed) {
            redirect('site/subscribe');
        }


        $onlineUsers = $this->user_model->getOnlineUsers($userId);
        if ($otherUserId) {
            $userExists = in_array($otherUserId, array_column($onlineUsers, 'id'));
            if (!$userExists) {
                $chatData = [
                    'myId' => $userId,
                    'otherId' => $otherUserId,
                ];
                $this->user_model->saveMyChat($chatData);
                $onlineUsers = $this->user_model->getOnlineUsers($userId);
                uasort($onlineUsers, function ($a, $b) {
                    return strcmp($b['id'], $a['id']);
                });
            } else {
                foreach ($onlineUsers as $key => $onlineuser) {
                    if ($onlineuser['id'] == $otherUserId) {
                        unset($onlineUsers[$key]);
                        $user = $this->user_model->getUserInfoByIdArray($otherUserId);
                        array_unshift($onlineUsers, $user);
                    }
                }
            }
        }
        // var_dump($onlineUsers);die;

        $allOnlineIds = '';
        $allOnline = array();
        foreach ($onlineUsers as $key => $onlineUser) {
            $allOnlineIds .= "'" . $onlineUser['id'] . "',";
            $allOnline[$key] = $onlineUser;
            $allOnline[$key]['lastMessage'] = $this->user_model->getLastMessage($userId, $onlineUser['id']);
        }

        $allOnlineIds = substr($allOnlineIds, 0, -1);

        $data['onlineUsers'] = $allOnline;
        $data['allOnlineIds'] = $allOnlineIds;


        $data['allUsers'] = $this->user_model->getAllUsers($userId);
        $data['allUsers'] = array_diff_key($data['allUsers'], $data['onlineUsers']);


        $firstUserId = null;

        foreach ($data['onlineUsers'] as $tempuser) {
            $firstUserId = $tempuser['id'];
            break;
        }

        $data['myId'] = $userId;
        $data['firstUserId'] = $firstUserId;
        $data['allMessages'] = $this->user_model->getMessages($userId, $firstUserId);
        $data['dateTime'] = '2024-01-01 01:01:00';
        if ($data['allMessages']) {

            $data['dateTime'] = $data['allMessages'][count($data['allMessages']) - 1]->createdDate;
        }


        $this->loadViews("chat", null, $data);
    }

    public function addMyChat()
    {
        $myId = $this->session->userdata('userId');
        $otherId = $this->security->xss_clean($this->input->post('toId'));


        $myChatData = [
            'myId' => $myId,
            'otherId' => $otherId,
        ];

        $result = $this->user_model->saveMyChat($myChatData);

        if ($result) {
            echo (json_encode($myChatData));
        } else {
            echo ('Network errro');
        }
    }

    public function removeMyChat()
    {
        $myId = $this->session->userdata('userId');
        $otherId = $this->security->xss_clean($this->input->post('otherId'));

        $result = $this->user_model->removeMyChat($myId, $otherId);

        if ($result) {
            echo ('chat user deleted');
        } else {
            echo ('Network errro');
        }
    }

    public function getMessages()
    {
        $myId = $this->session->userdata('userId');
        $toId = $this->input->post('toId');
        $messages = $this->user_model->getMessages($myId, $toId);
        $allMessages = array();
        foreach ($messages as $key => $message) {
            $allMessages[$key]['fromId'] = $message->fromId;
            $allMessages[$key]['toId'] = $message->toId;
            $allMessages[$key]['message'] = $message->message;
            $allMessages[$key]['dateTime'] = $message->createdDate;

            $messageDate = $message->createdDate;
            $dateNow = date("Y-m-d H:i:s");

            $dateDifference = getDateDifference($messageDate, $dateNow);
            $allMessages[$key]['dateDifference'] = $dateDifference;

            $nameParts = explode(' ', $name = $message->sender);
            $name = $nameParts[0];
            $allMessages[$key]['name'] = $name;
            $allMessages[$key]['image'] = $message->senderImage;
        }
        echo (json_encode($allMessages));
    }

    public function getNewMessages()
    {
        $myId = $this->session->userdata('userId');
        $userIds = $this->input->post('userIds');
        $lastMessageDateTime = $this->input->post('lastMessageDateTime');
        $messages = $this->user_model->getMessages($myId, $userIds, $lastMessageDateTime);
        $allMessages = array();
        foreach ($messages as $key => $message) {
            $allMessages[$key]['fromId'] = $message->fromId;
            $allMessages[$key]['toId'] = $message->toId;
            $allMessages[$key]['message'] = $message->message;
            $allMessages[$key]['dateTime'] = $message->createdDate;

            $messageDate = $message->createdDate;
            $dateNow = date("Y-m-d H:i:s");

            $dateDifference = getDateDifference($messageDate, $dateNow);
            $allMessages[$key]['dateDifference'] = $dateDifference;

            $nameParts = explode(' ', $name = $message->sender);
            $name = $nameParts[0];
            $allMessages[$key]['name'] = $name;
            $allMessages[$key]['image'] = $message->senderImage;
        }
        echo (json_encode($allMessages));
    }


    public function saveMessage()
    {
        $fromId = $this->session->userdata('userId');
        $toId = $this->security->xss_clean($this->input->post('toId'));
        $message = $this->security->xss_clean($this->input->post('message'));
        $dateNow = date("Y-m-d H:i:s");

        $messageData = [
            'fromId' => $fromId,
            'toId' => $toId,
            'message' => $message,
            'createdDate' => $dateNow,
        ];
        $result = $this->user_model->saveMessage($messageData);

        if ($result) {
            $fromUser = $this->user_model->getUserInfoByIdArray($fromId);
            $toUser = $this->user_model->getUserInfoByIdArray($toId);
            $config = array(
                'protocol' => 'smtp',
                'smtp_host' => 'ssl://mail.buzzwaretech.com',
                'smtp_port' => 465,
                'smtp_user' => 'testweb@buzzwaretech.com',
                'smtp_pass' => ',j8Og2d1Ty1%',
                'mailtype'  => 'html',
                'charset'   => 'iso-8859-1'
            );
            $this->load->library('email', $config);
            $this->email->from('testweb@buzzwaretech.com', 'Dentifyd Chat');
            $this->email->to('srtechs@gmail.com');

            $msg = "Hello " . $toUser['name'] . "<br><br>";
            $msg .= $fromUser['name'] . " has just sent you a message via chat, below is the message.<br><br>";
            $msg .= $message . "<br><br>";
            $msg .= "Regards<br>";
            $msg .= "Dentifyd Team";

            $this->email->subject('New chat message');
            $this->email->message($msg);

            $this->email->send();

            echo (json_encode($messageData));
        } else {
            echo ('Network errro');
        }
    }

    public function subscribe()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $this->loadViews("subscribe");
    }

    public function saveSubscription()
    {
        require FCPATH . 'vendor/autoload.php';

        $token = $this->input->post('stripeToken');

        $message = '';
        $success = false;
        if (!empty($token)) {

            // \Stripe\Stripe::setApiKey('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');    
            \Stripe\Stripe::setApiKey('sk_test_51NCpsrGnn1jsCOlLpDC7eKJ9dUvkhWLO20ZmieZNnoOIkMjtmrCJNfQJGjL7Ddd4mcDua4snJ6MqF0PiEJHf0GaU00b5qZIjqY');

            try {

                $userId = $this->session->userdata('userId');
                $user = $this->user_model->getUserInfoById($userId);

                $plan = $this->input->post('plan');
                $amount = 0;
                if ($plan == 'monthly') {
                    $amount = $this->input->post('monthly_fee');
                } else {

                    $amount = $this->input->post('yearly_fee');
                }

                $customer = \Stripe\Customer::create(array(
                    'name' => $user->name,
                    'email' => $user->email,
                    'source'  => $token,
                    'description' => 'Dentifyd User'
                ));

                $charge = \Stripe\Charge::create(array(
                    'customer' => $customer->id,
                    'amount'      => (float)$amount * 100,
                    // 'amount'      => 1 * 100,
                    'currency'    => 'USD',
                    'description' => 'Dentifyd chat subscription',
                ));

                $chargeJson = $charge->jsonSerialize();

                if ($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1) {

                    $subscriptionInfo = array(
                        'userId' => $userId,
                        'plan'      => $plan,
                        'fee'    => (float)$amount,
                        'status' => 'active',
                    );

                    $this->user_model->addSubscription($subscriptionInfo);
                    $message = 'Your have successfully subscribed to chat, enjoy!';
                    $success = true;
                }
            } catch (\Stripe\Error\Card $e) {

                $body = $e->getJsonBody();
                $err = $body['error'];
                $message = $err['message'];
            } catch (\Stripe\Error\RateLimit $e) {
                // Too many requests made to the API too quickly
                $message = $e->getMessage();
            } catch (\Stripe\Error\InvalidRequest $e) {
                // Invalid parameters were supplied to Stripe's API
                $message = $e->getMessage();
            } catch (\Stripe\Error\Authentication $e) {
                // Authentication with Stripe's API failed
                // (maybe you changed API keys recently)
                $message = $e->getMessage();
            } catch (\Stripe\Error\ApiConnection $e) {
                // Network communication with Stripe failed
                $message = $e->getMessage();
            } catch (\Stripe\Error\Base $e) {
                // Display a very generic error to the user, and maybe send
                // yourself an email
                $message = $e->getMessage();
            } catch (Exception $e) {
                // Something else happened, completely unrelated to Stripe
                $message = $e->getMessage();
            }
        } else {
            $message = "No stripe token";
            $error = true;
        }

        if ($success) {
            $this->session->set_flashdata('success', $message);
            redirect(base_url('site/chat'));
        } else {
            $this->session->set_flashdata('error', $message);
            redirect(base_url('site/subscribe'));
        }
    }



    public function quiz()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $this->loadViews("quiz");
    }

    public function getLatLong($address)
    {

        // $address = str_replace(" ", "+", $address);

        $json = file_get_contents("https://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&key=AIzaSyDfRI5hac8jwDvEQ1k2S5jfNEiNa9vcWhE");
        $json = json_decode($json);
        // var_dump($json);die;

        $lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
        $long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
        return ['lat' => $lat, 'long' => $long];
    }

    public function distance($lat1, $lon1, $lat2, $lon2, $unit)
    {

        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);

        $dis_in_km = $miles * 1.609344;
        $dis_in_km = round($dis_in_km, 2);

        return $dis_in_km;
    }

    public function stores()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $data['currentloc'] = '';
        $currentloc = $this->input->post('currentloc');
        if ($currentloc) {
            $data['currentloc'] = $currentloc;
            $userLatLong = $this->getLatLong($currentloc);
            $userLat = $userLatLong['lat'];
            $userLong = $userLatLong['long'];
            if ($userLat && $userLong) {
                $products = $this->user_model->getProducts();
                $productsNearMe = array();
                foreach ($products as $key => $product) {
                    $storeAddress = $product->storeAddress;
                    $storeLatLong = $this->getLatLong($storeAddress);
                    $storeLat = $storeLatLong['lat'];
                    $storeLong = $storeLatLong['long'];
                    if ($storeLat && $storeLong) {
                        $distance = $this->distance($userLat, $userLong, $storeLat, $storeLong, 'km');
                        if ($distance < 50) {
                            $productsNearMe[] = $product;
                        }
                    }
                }
                $data['products'] = $productsNearMe;
            } else {

                $data['products'] = $this->user_model->getProducts();
            }
        } else {

            $data['products'] = $this->user_model->getProducts();
        }

        $this->loadViews("store", null, $data);
    }
    public function buynow($productId)
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $data['product'] = $this->user_model->getProductById($productId);

        $this->loadViews("buynow", null, $data);
    }

    public function forum()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $userId = $this->session->userdata('userId');
        $user = $this->user_model->getUserInfoById($userId);
        $greeted = $user->greeted;
        $greetingMessage = '';
        if (!$greeted) {
            $updateData = ['greeted' => 1];
            $this->user_model->editUser($updateData, $userId);
            $greetingMessage = '<strong>Congratulations!</strong> Your account has been approved!';
        }
        $data['greetingMessage'] = $greetingMessage;
        $data['forumdata'] = $this->db->order_by('id', 'desc')->get('forums')->result_array();


        $this->loadViews("forum", $data);
    }
    public function processOrder()
    {
        require FCPATH . 'vendor/autoload.php';

        $productId = $this->input->post('productId');
        $token = $this->input->post('stripeToken');

        $message = '';
        $success = false;
        if (!empty($token)) {

            // \Stripe\Stripe::setApiKey('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');    
            \Stripe\Stripe::setApiKey('sk_test_51NCpsrGnn1jsCOlLpDC7eKJ9dUvkhWLO20ZmieZNnoOIkMjtmrCJNfQJGjL7Ddd4mcDua4snJ6MqF0PiEJHf0GaU00b5qZIjqY');

            try {

                $userId = $this->session->userdata('userId');
                $user = $this->user_model->getUserInfoById($userId);

                $product = $this->user_model->getProductById($productId);

                $customer = \Stripe\Customer::create(array(
                    'name' => $user->name,
                    'email' => $user->email,
                    'source'  => $token,
                    'description' => 'Dentifyd User'
                ));

                $charge = \Stripe\Charge::create(array(
                    'customer' => $customer->id,
                    'amount'      => (float)$product->price * 100,
                    // 'amount'      => 1 * 100,
                    'currency'    => 'USD',
                    'description' => $product->title,
                ));

                $chargeJson = $charge->jsonSerialize();

                if ($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1) {

                    $orderInfo = array(
                        'userId' => $userId,
                        'productId'      => $product->id,
                        'totalAmount'    => (float)$product->price,
                        'status' => 'paid',
                        'address' => $this->input->post('address'),
                        'city' => $this->input->post('city'),
                        'state' => $this->input->post('state'),
                        'country' => $this->input->post('country'),
                        'zip' => $this->input->post('zip'),
                        'phone' => $this->input->post('phone'),
                    );

                    $this->user_model->addOrder($orderInfo);
                    $message = 'Your order has been placed successfully.';
                    $success = true;
                }
            } catch (\Stripe\Error\Card $e) {

                $body = $e->getJsonBody();
                $err = $body['error'];
                $message = $err['message'];
            } catch (\Stripe\Error\RateLimit $e) {
                // Too many requests made to the API too quickly
                $message = $e->getMessage();
            } catch (\Stripe\Error\InvalidRequest $e) {
                // Invalid parameters were supplied to Stripe's API
                $message = $e->getMessage();
            } catch (\Stripe\Error\Authentication $e) {
                // Authentication with Stripe's API failed
                // (maybe you changed API keys recently)
                $message = $e->getMessage();
            } catch (\Stripe\Error\ApiConnection $e) {
                // Network communication with Stripe failed
                $message = $e->getMessage();
            } catch (\Stripe\Error\Base $e) {
                // Display a very generic error to the user, and maybe send
                // yourself an email
                $message = $e->getMessage();
            } catch (Exception $e) {
                // Something else happened, completely unrelated to Stripe
                $message = $e->getMessage();
            }
        } else {
            $message = "No stripe token";
            $error = true;
        }

        if ($success) {
            $this->session->set_flashdata('success', $message);
            redirect(base_url('site/store'));
        } else {
            $this->session->set_flashdata('error', $message);
            redirect(base_url('site/buynow/' . $productId));
        }
    }
    //forumdetail
    public function forumdetail($id)
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $data['forumdata'] = $this->db->where('id', $id)->get('forums')->row_array();

        $forumlike = false;
        $formunlike = false;
        $forumlikestatus = $this->db->where('forum_id', $id)->where('user_id', $this->session->userdata('userId'))->get('forum_likes')->row_array();
        if (!empty($forumlikestatus)) {
            if ($forumlikestatus['type'] == "like") {
                $forumlike = true;
            } else {
                $formunlike = true;
            }
        }
        $data['like'] = $forumlike;
        $data['unlike'] = $formunlike;

        $data['forumcomenstdata'] = $this->db->where('forum_id', $id)->get('forumsComments')->row_array();
        $data['forumid'] = $id;
        $this->loadViews("forumdetail", $data);
    }
    //commentssystem
    public function commentssystem($param1 = "")
    {
        if ($param1 == "add") {
            $data = $this->input->post();
            $data['user_id'] = $this->session->userdata('userId');
            $this->db->insert('forumsComments', $data);
            $forums = $this->db->where('id', $data['forum_id'])->get('forums')->row_array();
            $k['noofcoments'] = $forums['noofcoments'] + 1;
            $this->db->where('id', $data['forum_id'])->update('forums', $k);
            $d["success"] = 1;
            $d["noofcoments"] = $k['noofcoments'];

            echo  json_encode($d);
            exit;
        }
    }
    //site
    public function addforumdata()
    {
        $data = $this->input->post();
        $name = $_FILES["image"]["name"];
        $ext = end((explode(".", $name)));
        $id = time();
        if (move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/forums/' . $id . '.' . $ext)) {
            $data['image'] = base_url() . 'uploads/forums/' . $id . '.' . $ext;
        } else {
            $data['image'] = 'https://buzzwaretech.com/dentifyduser/assets/images/po1.jpg';
        }

        $this->db->insert('forums', $data);
        $this->session->set_flashdata('success', 'Data has been Added Sucessfully.');
        redirect(base_url() . 'site/forum');
    }
    public function readcomments($id)
    {
        $this->db->select('users.id as userId,users.name,users.image as userImage,forumsComments.*,forumsComments.id as fcmid');

        $this->db->order_by('forumsComments.id', 'desc');
        $this->db->where('forumsComments.forum_id', $id);
        $this->db->from('forumsComments');
        $this->db->join('users', 'forumsComments.user_id = users.id');

        $result = $this->db->get()->result_array();
        $data['comenstsinfo'] = $result;


        $j['commentsdata'] = $this->load->view("formscommenst", $data, true);
        $j['success'] = 1;
        echo json_encode($j);
    }
    public function getquestion()
    {
        $data['user_id'] = $this->session->userdata('userId');
        $answers = $this->db->where('user_id', $this->session->userdata('userId'))->get('filledquestion')->row_array();
        $answers = json_decode($answers['filleddata'], true);

        $a0res = array();
        $ans0 = $answers['answer0'];

        foreach ($ans0 as $val) {
            $ques = $this->db->where('id', (int)$val)->get('answers')->row_array();
            $a0res[] = $ques;
        }

        $a1res = array();
        $ans1 = $answers['answer1'];
        foreach ($ans1 as $val) {
            $ques = $this->db->where('id', (int)$val)->get('answers')->row_array();
            $a1res[] = $ques;
        }

        $data['a0res'] = $a0res;
        $data['a1res'] = $a1res;
        $this->loadViews("result", null, $data);
    }

    public function addmyanswern()
    {
        $data = $this->input->post();
        $quizidarray = $this->input->post('quizid');
        $totalquaiz = count($quizidarray);
        $corectans = 0;
        $woringans = 0;

        for ($i = 0; $i < count($quizidarray); $i++) {
            //   $data['qu']

            $quizid = $quizidarray[$i];
            $answergiven = $this->input->post('answer' . $quizid);
            $correctanswer = $this->input->post('correctanswer' . $quizid);
            if ($answergiven == $correctanswer) {
                $corectans = $corectans + 1;
            } else {
                $woringans = $woringans + 1;
            }
        }
        $j['total'] = $totalquaiz;
        $j['correct'] = $corectans;
        $j['wrong'] = $woringans;
        $j['content'] = 'oral'; // This is the view file without .php extension

        $this->loadViews('oralresult', $j);
    }
    public function addquestion()
    {


        $data['user_id'] = $this->session->userdata('userId');

        $data['filleddata'] = json_encode($this->input->post());;
        $before = $this->db->where('user_id', $this->session->userdata('userId'))->get('filledquestion')->row_array();
        if (empty($before)) {
            $this->db->insert('filledquestion', $data);
        } else {
            $this->db->where('user_id', $this->session->userdata('userId'))->update('filledquestion', $data);
        }
        $this->session->set_flashdata('success', 'Your Quiz has been submitted successfully');
        redirect(base_url() . 'site/getquestion');
    }
    public function likeSysytem($param1 = "")
    {
        //commentsike
        if ($param1 == "commentsike") {
            $data = $this->input->post();
            $data['user_id'] = $this->session->userdata('userId');
            $data['type'] = $this->input->post('type');
            $data['forum_id'] = $this->input->post('forum_id');
            $data['commentsid'] = $this->input->post('comments');



            echo json_encode($data);
        }
        if ($param1 == "forumlike") {
            $data['user_id'] = $this->session->userdata('userId');
            $data['type'] = $this->input->post('type');
            $data['forum_id'] = $this->input->post('forum_id');
            $forums = $this->db->where('id', $data['forum_id'])->get('forums')->row_array();
            if (empty($forums)) {
                $d["success"] = 2;
                echo  json_encode($d);
                exit;
            }
            $likedata = $this->db->where('forum_id', $data['forum_id'])->where('user_id', $data['user_id'])->get('forum_likes')->row_array();
            if (empty($likedata)) {
                $this->db->insert('forum_likes', $data);
                $likecout = 0;
                $dislikecount = 0;
                if ($data['type'] == "like") {
                    $likecout = 1;
                } else {
                    $dislikecount = 1;
                }
                $k['nooflikes'] = $forums['nooflikes'] + $likecout;
                $k['noofdislike'] = $forums['noofdislike'] + $dislikecount;
                $this->db->where('id', $data['forum_id'])->update('forums', $k);
                $d["success"] = 1;
                $d["nooflikes"] = $k['nooflikes'];
                $d["noofdislike"] = $k['noofdislike'];;
                $d['type'] = $data['type'];
                echo  json_encode($d);
                exit;
            } else {
                if ($likedata['type'] == $data['type']) {
                    $d["success"] = 1;
                    $d["nooflikes"] = $forums['nooflikes'];
                    $d["noofdislike"] = $forums['noofdislike'];;
                    $d['type'] = $data['type'];
                    echo  json_encode($d);
                    exit;
                } else {
                    $p['type'] = $data['type'];
                    $this->db->update('forum_likes', $p);
                    $likecout = 0;
                    $dislikecount = 0;
                    if ($data['type'] == "like") {
                        $likecout = $forums['nooflikes'] + 1;
                        $dislikecount = $forums['noofdislike'] - 1;
                    } else {
                        $likecout = $forums['nooflikes'] - 1;
                        $dislikecount = $forums['noofdislike'] + 1;
                    }
                    if ($likecout < 0) {
                        $likecout = 0;
                    }
                    if ($dislikecount < 0) {
                        $dislikecount = 0;
                    }
                    $k['nooflikes'] = $likecout;
                    $k['noofdislike'] = $dislikecount;
                    $this->db->where('id', $data['forum_id'])->update('forums', $k);
                    $d["success"] = 1;
                    $d["nooflikes"] = $k['nooflikes'];
                    $d["noofdislike"] = $k['noofdislike'];;
                    $d['type'] = $data['type'];
                    echo  json_encode($d);
                    exit;
                }
            }
        }
    }

    public function userprofile($userId = null)
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $myId = $this->session->userdata('userId');

        if (!$userId || $userId == $myId) {
            redirect('site/profile');
        }

        $data['user'] = $this->user_model->getUserInfo($userId);
        $data['questions'] = $this->user_model->getUserQuestions($userId);

        $this->loadViews("userprofile", null, $data);
    }

    public function overview()
    {
        $data = array();
        $this->loadViews("overview", null, $data);
    }
    public function community()
    {
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $userId = $this->session->userdata('userId');
        $user = $this->user_model->getUserInfoById($userId);
        $greeted = $user->greeted;
        $greetingMessage = '';
        if (!$greeted) {
            $updateData = ['greeted' => 1];
            $this->user_model->editUser($updateData, $userId);
            $greetingMessage = '<strong>Congratulations!</strong> Your account has been approved!';
        }
        $data['greetingMessage'] = $greetingMessage;
        $data['forumdata'] = $this->db->order_by('id', 'desc')->get('forums')->result_array();
        $data['content'] = 'community';
        $this->loadViews('community', $data);
        //        $this->loadViews("forum",$data);
        // This is the view file without .php extension



    }
    public function oral()
    {
        $data['content'] = 'oral'; // This is the view file without .php extension

        $this->loadViews('oral', $data);
    }
    public function chati()
    {
        $data['content'] = 'chat'; // This is the view file without .php extension

        $this->loadViews('chat', $data);
    }
    public function store()
    {
        $data['content'] = 'store';

        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $data['currentloc'] = '';
        $currentloc = $this->input->post('currentloc');
        if ($currentloc) {
            $data['currentloc'] = $currentloc;
            $userLatLong = $this->getLatLong($currentloc);
            $userLat = $userLatLong['lat'];
            $userLong = $userLatLong['long'];
            if ($userLat && $userLong) {
                $products = $this->user_model->getProducts();
                $productsNearMe = array();
                foreach ($products as $key => $product) {
                    $storeAddress = $product->storeAddress;
                    $storeLatLong = $this->getLatLong($storeAddress);
                    $storeLat = $storeLatLong['lat'];
                    $storeLong = $storeLatLong['long'];
                    if ($storeLat && $storeLong) {
                        $distance = $this->distance($userLat, $userLong, $storeLat, $storeLong, 'km');
                        if ($distance < 50) {
                            $productsNearMe[] = $product;
                        }
                    }
                }
                $data['products'] = $productsNearMe;
            } else {

                $data['products'] = $this->user_model->getProducts();
            }
        } else {

            $data['products'] = $this->user_model->getProducts();
        }

        // This is the view file without .php extension

        $this->loadViews('store', $data);
    }

    public function orders()
    {
        $data['content'] = 'orders'; // This is the view file without .php extension

        $this->loadViews('orders', $data);
    }
    public function socialinfluncers()
    {
        $data['content'] = 'socialinfluncers'; // This is the view file without .php extension

        $this->loadViews('socialinfluncers', $data);
    }
    public function influncer()
    {
        $data['content'] = 'influncer'; // This is the view file without .php extension

        $this->loadViews('influncer', $data);
    }
    public function profile()
    {
        $data['content'] = 'profile'; // This is the view file without .php extension

        $this->loadViews('profile', $data);
    }
    public function productdetail()
    {
        $data['content'] = 'productdetail'; // This is the view file without .php extension

        $this->loadViews('productdetail', $data);
    }


    public function profiles()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $userId = $this->session->userdata('userId');
        $data['user'] = $this->user_model->getUserInfo($userId);
        $data['questions'] = $this->user_model->getUserQuestions($userId);
        if (!$data['questions']) {
            redirect(base_url('site/questions'));
        }
        $this->loadViews("profile", null, $data);
    }


    public function editprofile()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $userId = $this->session->userdata('userId');
        $data['user'] = $this->user_model->getUserInfo($userId);
        $data['questions'] = $this->user_model->getUserQuestions($userId);
        $this->loadViews("editprofile", null, $data);
    }

    public function editquestions()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $userId = $this->session->userdata('userId');
        $data['user'] = $this->user_model->getUserInfo($userId);
        $data['questions'] = $this->user_model->getUserQuestions($userId);
        $this->loadViews("editquestions", null, $data);
    }

    public function updateProfile()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $userId = $this->session->userdata('userId');
        $name = $this->security->xss_clean($this->input->post('name'));
        $phone = $this->security->xss_clean($this->input->post('phone'));
        $address = $this->security->xss_clean($this->input->post('address'));
        $password = $this->security->xss_clean($this->input->post('password'));

        if (trim($password) != '') {
            $password = getHashedPassword($password);
            $userData = [
                'password' => $password,
                'name' => $name,
                'phone' => $phone,
                'address' => $address,
            ];
        } else {
            $userData = [
                'name' => $name,
                'phone' => $phone,
                'address' => $address,
            ];
        }

        $this->session->set_userdata('name', $name);


        if (!empty($_FILES['image']['name'])) {
            $config['upload_path'] = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['overwrite'] = false;
            $config['encrypt_name'] = TRUE;
            if (!is_dir($config['upload_path'])) die("THE UPLOAD DIRECTORY DOES NOT EXIST");
            $this->load->library('upload', $config);
            if ($this->upload->do_upload('image')) {
                $data = $this->upload->data();


                $image = base_url() . 'uploads/' . $data['file_name'];

                if (trim($password) != '') {
                    $password = getHashedPassword($password);
                    $userData = [
                        'password' => $password,
                        'image' => $image,
                        'name' => $name,
                        'phone' => $phone,
                        'address' => $address,
                    ];
                } else {
                    $userData = [
                        'image' => $image,
                        'name' => $name,
                        'phone' => $phone,
                        'address' => $address,
                    ];
                }

                $this->session->set_userdata('image', $image);
            }
        }

        //print_r($userData);
        $this->user_model->editUser($userData, $userId);

        $this->session->set_flashdata('success', 'Your Profile has been submitted successfully');
        redirect(base_url('site/editprofile'));
    }

    public function saveProfile()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }
        $userId = $this->session->userdata('userId');
        if (!$this->user_model->hasAnswers($userId)) {
            redirect('site');
        }
        $userId = $this->session->userdata('userId');
        /*
        $name = $this->security->xss_clean($this->input->post('name'));
        $phone = $this->security->xss_clean($this->input->post('phone'));
        $address = $this->security->xss_clean($this->input->post('address'));

        $userData = [
            'name' => $name,
            'phone' => $phone,
            'address' => $address,
        ];

        $this->user_model->editUser($userData, $userId);
*/
        if (!empty($_FILES['image']['name'])) {
            $config['upload_path'] = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['overwrite'] = false;
            $config['encrypt_name'] = TRUE;
            if (!is_dir($config['upload_path'])) die("THE UPLOAD DIRECTORY DOES NOT EXIST");
            $this->load->library('upload', $config);
            if ($this->upload->do_upload('image')) {
                $data = $this->upload->data();

                $problemUrgent = $this->security->xss_clean($this->input->post('problemUrgent'));
                $treatment = $this->security->xss_clean($this->input->post('treatment'));
                $travelDistance = $this->security->xss_clean($this->input->post('travelDistance'));
                $smokeDrink = $this->security->xss_clean($this->input->post('smokeDrink'));
                $teethBrush = $this->security->xss_clean($this->input->post('teethBrush'));
                $disabilities = $this->security->xss_clean($this->input->post('disabilities'));
                $important = $this->security->xss_clean($this->input->post('important'));
                $image = $data['file_name'];

                $answersData = [
                    'userId' => $userId,
                    'problemUrgent' => $problemUrgent,
                    'treatment' => $treatment,
                    'travelDistance' => $travelDistance,
                    'smokeDrink' => $smokeDrink,
                    'teethBrush' => $teethBrush,
                    'disabilities' => $disabilities,
                    'important' => $important,
                    'image' => $image,
                ];

                $this->user_model->editQuestions($answersData, $userId);

                $this->user_model->editQuestions($answersData, $userId);
                redirect(base_url('site/profile'));
            } else {

                $this->session->set_flashdata('error', 'Your image is not in proper format and or size');
                redirect(base_url('site/editquestions'));
            }
        } else {
            $problemUrgent = $this->security->xss_clean($this->input->post('problemUrgent'));
            $treatment = $this->security->xss_clean($this->input->post('treatment'));
            $travelDistance = $this->security->xss_clean($this->input->post('travelDistance'));
            $smokeDrink = $this->security->xss_clean($this->input->post('smokeDrink'));
            $teethBrush = $this->security->xss_clean($this->input->post('teethBrush'));
            $disabilities = $this->security->xss_clean($this->input->post('disabilities'));
            $important = $this->security->xss_clean($this->input->post('important'));

            $answersData = [
                'problemUrgent' => $problemUrgent,
                'treatment' => $treatment,
                'travelDistance' => $travelDistance,
                'smokeDrink' => $smokeDrink,
                'teethBrush' => $teethBrush,
                'disabilities' => $disabilities,
                'important' => $important,
            ];

            $this->user_model->editQuestions($answersData, $userId);
            redirect(base_url('site/profile'));
        }
    }



    public function questions()
    {
        if (!$this->isAdmin()) {
            redirect('login');
        }

        $this->loadViews("questions");
    }

    public function saveAnswers()
    {

        if (!empty($_FILES['image']['name'])) {

            // var_dump($this->input->post());die;
            $config['upload_path'] = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['overwrite'] = false;
            $config['encrypt_name'] = TRUE;
            if (!is_dir($config['upload_path'])) die("THE UPLOAD DIRECTORY DOES NOT EXIST");
            $this->load->library('upload', $config);
            if ($this->upload->do_upload('image')) {
                $data = $this->upload->data();

                $userId = $this->session->userdata('userId');
                $problemUrgent = $this->security->xss_clean($this->input->post('problemUrgent'));
                $treatment = $this->security->xss_clean($this->input->post('treatment'));
                $travelDistance = $this->security->xss_clean($this->input->post('travelDistance'));
                $smokeDrink = $this->security->xss_clean($this->input->post('smokeDrink'));
                $teethBrush = $this->security->xss_clean($this->input->post('teethBrush'));
                $disabilities = $this->security->xss_clean($this->input->post('disabilities'));
                $important = $this->security->xss_clean($this->input->post('important'));
                $image = $data['file_name'];

                $answersData = [
                    'userId' => $userId,
                    'problemUrgent' => $problemUrgent,
                    'treatment' => $treatment,
                    'travelDistance' => $travelDistance,
                    'smokeDrink' => $smokeDrink,
                    'teethBrush' => $teethBrush,
                    'disabilities' => $disabilities,
                    'important' => $important,
                    'image' => $image,
                ];

                if ($this->user_model->saveQuestions($answersData)) {
                    $this->session->set_flashdata('success', 'Your profile is complete now.');
                    redirect(base_url('site/forum'));
                } else {
                    $this->session->set_flashdata('error', 'System error, please try again');
                    redirect(base_url('site/questions'));
                }
            } else {

                $this->session->set_flashdata('error', 'Your image is not in proper format and or size');
                redirect(base_url('site/questions'));
            }
        } else {
            $userId = $this->session->userdata('userId');
            $problemUrgent = $this->security->xss_clean($this->input->post('problemUrgent'));
            $treatment = $this->security->xss_clean($this->input->post('treatment'));
            $travelDistance = $this->security->xss_clean($this->input->post('travelDistance'));
            $smokeDrink = $this->security->xss_clean($this->input->post('smokeDrink'));
            $teethBrush = $this->security->xss_clean($this->input->post('teethBrush'));
            $disabilities = $this->security->xss_clean($this->input->post('disabilities'));
            $important = $this->security->xss_clean($this->input->post('important'));

            $answersData = [
                'userId' => $userId,
                'problemUrgent' => $problemUrgent,
                'treatment' => $treatment,
                'travelDistance' => $travelDistance,
                'smokeDrink' => $smokeDrink,
                'teethBrush' => $teethBrush,
                'disabilities' => $disabilities,
                'important' => $important,
            ];

            if ($this->user_model->saveQuestions($answersData)) {
                $this->session->set_flashdata('success', 'Your answers has been saved.');
                redirect(base_url('site/forum'));
            } else {
                $this->session->set_flashdata('error', 'System error, please try again');
                redirect(base_url('site/questions'));
            }
        }
    }

    public function signup($verror = false)
    {
        if ($this->isAdmin()) {
            redirect('site');
        }

        $data['verrors'] = $verror;

        $this->load->view("signup", $data);
        // $this->load->view("signup", null, $data);
    }

    public function dosignup()
    {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('name', 'Name', 'trim|required');
        $this->form_validation->set_rules('address', 'Address', 'trim|required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]');
        $this->form_validation->set_rules('password', 'Password', 'required|max_length[20]');


        if ($this->form_validation->run() == FALSE) {

            $this->signup(true);
        } else {
            $name = $this->security->xss_clean($this->input->post('name'));
            $address = $this->security->xss_clean($this->input->post('address'));
            $email = strtolower($this->security->xss_clean($this->input->post('email')));
            $password = $this->input->post('password');


            $userInfo = array(
                'name' => $name,
                'address' => $address,
                'email' => $email,
                'password' => getHashedPassword($password),
                'role' => 'user',
                'isOnline' => 1,
            );

            $this->load->model('user_model');
            $result = $this->user_model->addNewUser($userInfo);

            if ($result > 0) {
                $user = $this->login_model->loginMe($email, $password);
                $sessionArray = array(
                    'userId' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => $user->role,
                    'isLoggedIn' => TRUE
                );

                $this->session->set_userdata($sessionArray);

                $this->session->set_flashdata('success', 'New User created successfully');
                redirect('site/questions');
            } else {
                $this->session->set_flashdata('error', 'User creation failed');
                redirect('site/signup');
            }
        }
    }



    // function addNewUser()
    // {
    //     if(!$this->isAdmin())
    //     {
    //         $this->loadThis();
    //     }
    //     else
    //     {
    //         $this->load->library('form_validation');

    //         $this->form_validation->set_rules('name','Full Name','trim|required|max_length[128]');
    //         $this->form_validation->set_rules('email','Email','trim|required|valid_email|max_length[128]');
    //         $this->form_validation->set_rules('password','Password','required|max_length[20]');
    //         $this->form_validation->set_rules('cpassword','Confirm Password','trim|required|matches[password]|max_length[20]');
    //         $this->form_validation->set_rules('phone','Phone Number','required|min_length[10]');
    //         $this->form_validation->set_rules('agent','Agent','required');

    //         if($this->form_validation->run() == FALSE)
    //         {
    //             redirect('site/signup');
    //         }
    //         else
    //         {
    //             $name = ucwords(strtolower($this->security->xss_clean($this->input->post('name'))));
    //             $email = strtolower($this->security->xss_clean($this->input->post('email')));
    //             $password = $this->input->post('password');
    //             $phone = $this->security->xss_clean($this->input->post('phone'));
    //             $balance = $this->security->xss_clean($this->input->post('balance'));
    //             $agent = $this->security->xss_clean($this->input->post('agent'));
    //             $role = 'user';

    //             $userInfo = array(
    //                             'name'=> $name,
    //                             'email'=>$email,
    //                             'password'=>getHashedPassword($password),
    //                             'phone'=>$phone,
    //                             'balance'=>$balance,
    //                             'role'=>$role,
    //                             'parent_id'=>$agent,
    //                             'isOnline'=>$agent,
    //                         );

    //             $this->load->model('user_model');
    //             $result = $this->user_model->addNewUser($userInfo);

    //             if($result > 0){
    //                 $this->session->set_flashdata('success', 'New User created successfully');
    //             } else {
    //                 $this->session->set_flashdata('error', 'User creation failed');
    //             }

    //             redirect('site/signup');
    //         }
    //     }
    // }

    // public function addNewUser()
    // {
    //     log_message('debug', 'addNewUser method started');
    //     $data = $this->input->post();
    //     print_r($data);
    //     exit;
    //     if (!$this->isAdmin()) {
    //         $this->loadThis();
    //     } else {
    //         $this->load->library('form_validation');
    //         $this->load->library('upload');

    //         // Existing validation rules
    //         $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|max_length[128]');
    //         $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|max_length[128]');
    //         $this->form_validation->set_rules('dob', 'Date of Birth', 'trim|required');
    //         $this->form_validation->set_rules('gender', 'Gender', 'trim|required');
    //         $this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email|max_length[128]');
    //         $this->form_validation->set_rules('mobile_number', 'Mobile Number', 'trim|required|min_length[10]');
    //         $this->form_validation->set_rules('password', 'Password', 'required|max_length[20]');
    //         $this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required|matches[password]|max_length[20]');
    //         $this->form_validation->set_rules('address', 'Address', 'trim|required');
    //         $this->form_validation->set_rules('suite_number', 'Suite Number', 'trim');
    //         $this->form_validation->set_rules('city', 'City', 'trim|required');
    //         $this->form_validation->set_rules('state', 'State', 'trim|required');
    //         $this->form_validation->set_rules('zip_code', 'Zip Code', 'trim|required');
    //         $this->form_validation->set_rules('complaint', 'Complaint', 'trim|required');
    //         $this->form_validation->set_rules('problem', 'Problem Duration', 'trim|required');
    //         $this->form_validation->set_rules('symptoms', 'Symptoms', 'trim|required');
    //         $this->form_validation->set_rules('discuss', 'Discussion Timing', 'trim|required');
    //         $this->form_validation->set_rules('medicialcondition', 'Medical Condition', 'trim|required');
    //         $this->form_validation->set_rules('mediciation', 'Medication', 'trim|required');
    //         $this->form_validation->set_rules('willingToTravel', 'Willing to Travel', 'trim|required');
    //         $this->form_validation->set_rules('importantClinic', 'Important Clinic Factor', 'trim|required');
    //         $this->form_validation->set_rules('knowAbout', 'Additional Information', 'trim|required');

    //         if ($this->form_validation->run() == FALSE) {
    //             // Validation failed, load the form again with errors
    //             $this->addUser();
    //         } else {
    //             // Form validation passed, process user data
    //             $userInfo = array(
    //                 'first_name' => ucwords(strtolower($this->security->xss_clean($this->input->post('first_name')))),
    //                 'last_name' => ucwords(strtolower($this->security->xss_clean($this->input->post('last_name')))),
    //                 'dob' => $this->security->xss_clean($this->input->post('dob')),
    //                 'gender' => $this->security->xss_clean($this->input->post('gender')),
    //                 'email' => strtolower($this->security->xss_clean($this->input->post('email'))),
    //                 'mobile_number' => $this->security->xss_clean($this->input->post('mobile_number')),
    //                 'password' => getHashedPassword($this->input->post('password')),
    //                 'address' => $this->security->xss_clean($this->input->post('address')),
    //                 'suite_number' => $this->security->xss_clean($this->input->post('suite_number')),
    //                 'city' => $this->security->xss_clean($this->input->post('city')),
    //                 'state' => $this->security->xss_clean($this->input->post('state')),
    //                 'zip_code' => $this->security->xss_clean($this->input->post('zip_code')),
    //                 'complaint' => $this->security->xss_clean($this->input->post('complaint')),
    //                 'problem' => $this->security->xss_clean($this->input->post('problem')),
    //                 'symptoms' => $this->security->xss_clean($this->input->post('symptoms')),
    //                 'discuss' => $this->security->xss_clean($this->input->post('discuss')),
    //                 'medicialcondition' => $this->security->xss_clean($this->input->post('medicialcondition')),
    //                 'mediciation' => $this->security->xss_clean($this->input->post('mediciation')),
    //                 'willingToTravel' => $this->security->xss_clean($this->input->post('willingToTravel')),
    //                 'importantClinic' => $this->security->xss_clean($this->input->post('importantClinic')),
    //                 'knowAbout' => $this->security->xss_clean($this->input->post('knowAbout')),
    //                 'role' => 'user',
    //                 'parent_id' => $this->security->xss_clean($this->input->post('agent')),
    //                 'treatment' => json_encode($this->input->post('treatment') ?? [])
    //             );

    //             // Handle file uploads
    //             $files = ['upload_image1', 'upload_image2', 'upload_image3', 'upload_image4', 'upload_image5', 'upload_image6'];

    //             foreach ($files as $file) {
    //                 if (!empty($_FILES[$file]['name'])) {
    //                     $config['upload_path'] = './uploads/';
    //                     $config['allowed_types'] = 'jpg|jpeg|png';
    //                     $config['max_size'] = 2048;
    //                     $config['file_name'] = $_FILES[$file]['name'];

    //                     $this->upload->initialize($config);

    //                     if ($this->upload->do_upload($file)) {
    //                         $userInfo[$file] = $this->upload->data('file_name');
    //                     } else {
    //                         log_message('error', 'Upload error for ' . $file . ': ' . $this->upload->display_errors());
    //                         $userInfo[$file] = null;
    //                     }
    //                 }
    //             }

    //             $this->load->model('user_model');
    //             $result = $this->user_model->addNewUser($userInfo);

    //             if ($result > 0) {
    //                 $this->session->set_flashdata('success', 'New User created successfully');
    //             } else {
    //                 log_message('error', 'User creation failed in model');
    //                 $this->session->set_flashdata('error', 'User creation failed');
    //             }

    //             // Redirect to signup page
    //             redirect('site/signup');
    //         }
    //     }
    // }


    // public function addNewUser()
    // {
    //     log_message('debug', 'addNewUser method started');

    //     if (!$this->isAdmin()) {
    //         $this->loadThis();
    //     } else {
    //         $this->load->library('form_validation');
    //         $this->load->library('upload');


    //         $this->form_validation->set_rules('first_name', 'First Name', 'trim|required');
    //         $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
    //         $this->form_validation->set_rules('dob', 'Date of Birth', 'trim|required');
    //         $this->form_validation->set_rules('gender', 'Gender', 'trim|required');
    //         $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
    //         $this->form_validation->set_rules('phone', 'Phone', 'trim|required');
    //         $this->form_validation->set_rules('password', 'Password', 'trim|required');
    //         $this->form_validation->set_rules('confirmPassword', 'Confirm Password', 'trim|required|matches[password]');
    //         $this->form_validation->set_rules('address', 'Address', 'trim|required');
    //         $this->form_validation->set_rules('city', 'City', 'trim|required');
    //         $this->form_validation->set_rules('state', 'State', 'trim|required');
    //         $this->form_validation->set_rules('zipCode', 'Zip Code', 'trim|required');

    //         if ($this->form_validation->run() == FALSE) {

    //             $this->addNewUserView();
    //         } else {

    //             $data = $this->input->post();

    //             $uploaded_files = [];
    //             for ($i = 1; $i <= 6; $i++) {
    //                 $file_field = 'upload_image' . $i;
    //                 if (!empty($_FILES[$file_field]['name'])) {
    //                     $config['upload_path'] = './uploads/';
    //                     $config['allowed_types'] = 'gif|jpg|png';
    //                     $config['max_size'] = 2048; // 2MB
    //                     $config['file_name'] = uniqid() . '_' . $_FILES[$file_field]['name'];

    //                     $this->upload->initialize($config);

    //                     if ($this->upload->do_upload($file_field)) {
    //                         $upload_data = $this->upload->data();
    //                         $uploaded_files[$file_field] = $upload_data['file_name'];
    //                     } else {
    //                         // Handle upload error
    //                         $error = $this->upload->display_errors();
    //                         log_message('error', 'File upload error: ' . $error);
    //                         $this->session->set_flashdata('error', $error);
    //                         redirect('addNewUserView');
    //                     }
    //                 }
    //             }


    //             $userInfo = [
    //                 'first_name' => $data['first_name'],
    //                 'last_name' => $data['last_name'],
    //                 'dob' => $data['dob'],
    //                 'gender' => $data['gender'],
    //                 'email' => $data['email'],
    //                 'phone' => $data['phone'],
    //                 'password' => password_hash($data['password'], PASSWORD_BCRYPT),
    //                 'address' => $data['address'],
    //                 'suite_number' => $data['suiteNumber'],
    //                 'city' => $data['city'],
    //                 'state' => $data['state'],
    //                 'zip_code' => $data['zipCode'],
    //                 'main_reason' => $data['mainReason'],
    //                 'hear_about' => $data['hearAbout'],
    //                 'agree' => $data['agree'],
    //                 'complaint' => $data['complaint'],
    //                 'problem' => $data['problem'],
    //                 'symptoms' => $data['symptoms'],
    //                 'discuss' => $data['discuss'],
    //                 'medical_condition' => $data['medicalCondition'],
    //                 'medication' => $data['medication'],
    //                 'treatments' => $data['treatments'],
    //                 'willing_to_travel' => $data['willingToTravel'],
    //                 'important_clinic' => $data['importantClinic'],
    //                 'know_about' => $data['knowAbout']
    //             ];

    //             // Add uploaded file names to userInfo
    //             foreach ($uploaded_files as $key => $value) {
    //                 $userInfo[$key] = $value;
    //             }

    //             // Insert data into database
    //             $this->load->model('user_model');
    //             $insert_id = $this->user_model->addNewUser($userInfo);

    //             if ($insert_id) {
    //                 $this->session->set_flashdata('success', 'New user added successfully.');
    //                 redirect('userList');
    //             } else {
    //                 $this->session->set_flashdata('error', 'User addition failed.');
    //                 redirect('addNewUserView');
    //             }
    //         }
    //     }
    // }

    // $data = $this->input->post();
    // print_r($data);
    // print_r($_FILES["upload_image1"]["name"]);
    // print_r($_FILES["upload_image2"]["name"]);
    // print_r($_FILES["upload_image3"]["name"]);
    // print_r($_FILES["upload_image4"]["name"]);
    // print_r($_FILES["upload_image5"]["name"]);
    // print_r($_FILES["upload_image6"]["name"]);

    // exit;

    public function addNewUser()
    {
        // log_message('debug', 'addNewUser method started');
    
    
        $this->load->library('upload');
    
        // Retrieve form data
        $data = $this->input->post();
        

        $config['upload_path']          = './uploads/';
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = 100;
        $config['max_width']            = 1024;
        $config['max_height']           = 768;

        $this->load->library('upload', $config);
    
        // Fields to handle file uploads
        $imageFields = ['upload_image1', 'upload_image2', 'upload_image3', 'upload_image4', 'upload_image5', 'upload_image6'];
        foreach ($imageFields as $field) {
           
            if (!empty($_FILES[$field]['name'])) {

                $uploaddir = 'uploads/'.time().rand().$_FILES[$field]['name'];

                if (move_uploaded_file($_FILES[$field]['tmp_name'], $uploaddir)) {

              //  echo $_FILES[$field]['name'].'---'.$field;
//             $config['file_name'] = time() . '_' . $_FILES[$field]['name'];
   
    

                    $data[$field] = $uploaddir;
                } else {
                   // log_message('error', $this->upload->display_errors());
                    $data[$field] = null; // Set to null if upload fails
                }
            } else {
                $data[$field] = null; // Set to null if no file is uploaded
            }
        }
    
        // Prepare data for insertion into the database
        $insertData = [
            'first_name' => $data['first_name'] ?? null,
            'last_name' => $data['last_name'] ?? null,

            'dob' => $data['dob'] ?? null,
            'gender' => $data['gender'] ?? null,
            'email' => $data['email'] ?? null,
            'phone' => $data['phone'] ?? null,
            'password' =>getHashedPassword($data['password']),
            'address' => $data['address'] ?? null,
            'suite_number' => $data['suite_number'] ?? null,
            'city' => $data['city'] ?? null,
            'state' => $data['state'] ?? null,
            'zip_code' => $data['zip_code'] ?? null,
            'main_reason' => $data['main_reason'] ?? null,
            'hear_about' => $data['hear_about'] ?? null,
            'agree' => isset($data['agree']) ? 1 : 0,
            'complaint' => $data['complaint'] ?? null,
            'problem' => $data['problem'] ?? null,
            'symptoms' => $data['symptoms'] ?? null,
            'discuss' => $data['discuss'] ?? null,
            'medical_condition' => $data['medical_condition'] ?? null,
            'medication' => $data['medication'] ?? null,
            'treatments' => $data['treatments'] ?? null,
            'willingToTravel' => $data['willingToTravel'] ?? 0,
            'importantClinic' => $data['importantClinic'] ?? null,
            'knowAbout' => $data['knowAbout'] ?? null,
            'upload_image1' => $data['upload_image1'],
            'upload_image2' => $data['upload_image2'],
            'upload_image3' => $data['upload_image3'],
            'upload_image4' => $data['upload_image4'],
            'upload_image5' => $data['upload_image5'],
            'upload_image6' => $data['upload_image6']
        ];
    
      
        // Load the model and insert the data into the database
        $this->load->model('User_model');
        $inserted = $this->User_model->insertUser($insertData);
    
        if ($inserted) {
            $this->session->set_flashdata('success', 'User added successfully.');
        } else {
            $this->session->set_flashdata('error', 'User addition failed.');
        }
    
        redirect('user/addNew');
    }
    
    






    function checkEmailExists()
    {
        $userId = $this->input->post("userId");
        $email = $this->input->post("email");

        if (empty($userId)) {
            $result = $this->user_model->checkEmailExists($email);
        } else {
            $result = $this->user_model->checkEmailExists($email, $userId);
        }

        if (empty($result)) {
            echo ("true");
        } else {
            echo ("false");
        }
    }

    function getUserInfo()
    {
        $userId = $this->input->post("userId");
        $userData = $this->user_model->getUserInfoById($userId);
        echo (json_encode($userData));
    }

    function logout()
    {
        $userId = $this->session->userdata('userId');
        $userData = array('isOnline' => 0);
        $this->user_model->editUser($userData, $userId);
        session_unset();
        session_destroy();
        redirect('login');
    }
}