<?php

use PHPMailer\PHPMailer\PHPMailer;

require_once __DIR__ . '/functions/auth.php';

class Token
{

    public function checkToken($token, $unit)
    {

        $jwt = new Authentication();
        $d = $jwt->decodeJwtToken($token);
        $email = $d->jti;




        require __DIR__ . '/../bootstrap.php';
        require __DIR__ . '/models/GeneralUser.php';
        require __DIR__ . '/models/CollegeUser.php';

        if ($unit == 'admin') {
            return $entityManager->getRepository('CollegeUser')->checkEmailToken($email, $token);
        } elseif ($unit == 'FACULTY') {
            return $entityManager->getRepository('GeneralUser')->checkEmailToken($email, $token);
        } elseif ($unit == 'ALUMNI') {
            return true;
        } elseif ($unit == 'STUDENT') {
            if ($entityManager->getRepository('GeneralUser')->checkEmailToken($email, $token) == false) {
                return $entityManager->getRepository('AdmissionTemp')->checkEmailToken($email, $token);
            } else {
                return true;
            }
        }
    }

    public function checkTokenWithEmail($token)
    {
        $jwt = new Authentication();
        $d = $jwt->decodeJwtToken($token);
        $email = $d->jti;
        return $email;
    }
}
class ApiKey
{
    public function getLog($apikey)
    {
        if ($apikey == getenv("HTTP_ROLE_SUPER_ADMIN")) {
            $role = "SUPERADMIN";
        } else if ($apikey == getenv("HTTP_ROLE_EXECUTIVE")) {
            $role = "EXECUTIVE";
        } else if ($apikey == getenv("HTTP_ROLE_INTERNAL")) {
            $role = "INTERNAL";
        }

        if ($role == 'SUPERADMIN') {
            return $array = explode("\n", file_get_contents('../logs/app.log'));
        }
    }
}

// class ChangeDate{
//     public function change_date($date){
//         return date('d-m-Y',strtotime($date));
//     }
// }

class SendSMS
{

    public function send_sms_register($body, $role)
    {
        // Authorisation details.
        $username = "info@corexx.in";
        $hash = "47c622878bb3000fe0a2f82a7c96620fe4b3d7ad70520138def91fe6bb423d43";

        // Config variables. Consult http://api.textlocal.in/docs for more info.
        $test = "0";

        // Data for text message. This is the text message data.
        $sender = "COREXX"; // This is who the message appears to be from.
        $numbers = $body['phone']; // A single number or a comma-seperated list of numbers

        $link = '';
        if ($role == 'STUDENT') {
            $link = 'https://student.democollege.ac.in';
        } else if ($role == 'FACULTY') {
            $link = 'https://user.democollege.ac.in';
        } else {
            $link = 'https://user.democollege.ac.in';
        }

        $message = "Visit " . $link . " with Username: " . $body['email'] . ' Password: ' . $body['password']."\n\n- Corexx";
        // 612 chars or less
        // A single number or a comma-seperated list of numbers
        $message = rawurlencode($message);
        $data = "username=" . $username . "&hash=" . $hash . "&message=" . $message . "&sender=" . $sender . "&numbers=" . $numbers . "&test=" . $test;
        $ch = curl_init('http://api.textlocal.in/send/?');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch); // This is the result from the API
        curl_close($ch);

        return true;
    }

    public function send_sms_leave($body)
    {
        // Authorisation details.
        $username = "info@corexx.in";
        $hash = "47c622878bb3000fe0a2f82a7c96620fe4b3d7ad70520138def91fe6bb423d43";

        // Config variables. Consult http://api.textlocal.in/docs for more info.
        $test = "0";

        // Data for text message. This is the text message data.
        $sender = "COREXX"; // This is who the message appears to be from.
        $numbers = $body['phone']; // A single number or a comma-seperated list of numbers

        $message = "Your application of " . $body['leave_type'] . ' from ' . $body['start_date'] . ' to ' . $body['end_date'] . ' has been ' . $body['action'];
        // 612 chars or less
        // A single number or a comma-seperated list of numbers
        $message = rawurlencode($message);
        $data = "username=" . $username . "&hash=" . $hash . "&message=" . $message . "&sender=" . $sender . "&numbers=" . $numbers . "&test=" . $test;
        $ch = curl_init('http://api.textlocal.in/send/?');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch); // This is the result from the API
        curl_close($ch);

        return true;
    }

    public function send_sms_leave_apply($body)
    {
        // Authorisation details.
        $username = "info@corexx.in";
        $hash = "47c622878bb3000fe0a2f82a7c96620fe4b3d7ad70520138def91fe6bb423d43";

        // Config variables. Consult http://api.textlocal.in/docs for more info.
        $test = "0";

        // Data for text message. This is the text message data.
        $sender = "COREXX"; // This is who the message appears to be from.
        $numbers = $body['phone']; // A single number or a comma-seperated list of numbers

        $message = "Your leave application for " . $body['leave_type'] . " has been received successfully. Further updates will be notified via SMS. Thank you.";
        // 612 chars or less
        // A single number or a comma-seperated list of numbers
        $message = rawurlencode($message);
        $data = "username=" . $username . "&hash=" . $hash . "&message=" . $message . "&sender=" . $sender . "&numbers=" . $numbers . "&test=" . $test;
        $ch = curl_init('http://api.textlocal.in/send/?');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch); // This is the result from the API
        curl_close($ch);

        return true;
    }

    public function send_sms_forgot_password($body)
    {
        // MSG91 credentials
        $authKey = "468487AGnDLzkHd7MF68c27ae5P1"; // replace with your MSG91 auth key
        $templateId = "68c277efca732e55940af512"; // replace with your MSG91 template id

        // Extract and sanitize phone
        $numbers = preg_replace('/\D/', '', $body['phone']); // keep only digits

        // If 10 digits, prepend country code 91 (India)
        if (strlen($numbers) === 10) {
            $numbers = "91" . $numbers;
        }

        // OTP
        $otp = $body['otp'];

        // Prepare MSG91 request body
        $postData = [
            "template_id" => $templateId,
            "short_url" => "0",
            "recipients" => [
                [
                    "mobiles" => $numbers,
                    "var" => $otp // {{OTP}} must exist in your MSG91 template
                ]
            ]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://control.msg91.com/api/v5/flow/");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "accept: application/json",
            "authkey: " . $authKey,
            "content-type: application/json"
        ]);

        $result = curl_exec($ch);
        curl_close($ch);

        // Always return true (like Textlocal function)
        return true;
    }

    public function send_sms_admission_otp($body)
    {
        // MSG91 credentials
        $authKey = "468487AGnDLzkHd7MF68c27ae5P1"; // replace with your MSG91 auth key
        $templateId = "68c277efca732e55940af512"; // replace with your MSG91 template id

        // Extract and sanitize phone
        $numbers = preg_replace('/\D/', '', $body['phone']); // keep only digits

        // If 10 digits, prepend country code 91 (India)
        if (strlen($numbers) === 10) {
            $numbers = "91" . $numbers;
        }

        // OTP
        $otp = $body['otp'];

        // Prepare MSG91 request body
        $postData = [
            "template_id" => $templateId,
            "short_url" => "0",
            "recipients" => [
                [
                    "mobiles" => $numbers,
                    "var" => $otp // {{OTP}} must exist in your MSG91 template
                ]
            ]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://control.msg91.com/api/v5/flow/");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "accept: application/json",
            "authkey: " . $authKey,
            "content-type: application/json"
        ]);

        $result = curl_exec($ch);
        curl_close($ch);

        // Always return true (like Textlocal function)
        return true;
    }
}

class SendEmail
{

    public function send_mail_new_user($to, $password)
    {
        $mail = new PHPMailer(true); // Passing `true` enables exceptions
        try {
            //Server settings
            $mail->SMTPDebug = 0; // Enable verbose debug output
            $mail->isSMTP(); // Set mailer to use SMTP
            $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
            $mail->SMTPAuth = true; // Enable SMTP authentication
            $mail->Username = getenv('MY_EMAIL'); // SMTP username
            $mail->Password = getenv('MY_PASSWORD'); // SMTP password
            $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 587; // TCP port to connect to

            //Recipients
            $mail->setFrom('no-reply@corexx.in', 'AEC - WEB - PORTAL');
            $mail->addAddress($to); // Add a recipient
            //$mail->addReplyTo('info@example.com', 'Information');
            //$mail->addCC('cc@example.com');
            //$mail->addBCC('bcc@example.com');

            //Attachments
            //$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
            //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name

            //Content
            $mail->isHTML(true); // Set email format to HTML
            $mail->Subject = 'Your registration have been completed';
            $mail->Body = '<h3>Thankyou for Registering With us</h3><br/><br/> Username: <b>' . $to . '</b> <br/>
            Password: <b>' . $password . '</b><br/><hr/><br/><h5 style="color:red">Please change the password after first login. Thank you.</h5>';
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $mail->send();
            return true;
        } catch (Exception $e) {
            return 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
        }
    }
}

class FileUpload
{ //protected $file_name = array();

    public function deleteFile($type, $image_file)
    {
        $path = __DIR__ . '/uploads/' . $type . '/' . $image_file;
        if (file_exists($path)) {
            if (unlink($path)) {
                return true;
            }
        }
        return false;
    }

    public function addFile($file_name, $body)
    {

        $type = $body['type'];
        $info = getimagesize($file_name['tmp_name']);

        $path = $this->createFile($file_name, $type);

        //mime type
        $ext = pathinfo($file_name['name'], PATHINFO_EXTENSION);

        if ($ext == 'pdf') {
            $mime = "application/pdf";
        } else {
            $mime = $info['mime'];
        }

        if ($path != false) {
            $a = array();
            $a['type'] = $type;
            $a['path'] = $path;
            $a['mime'] = $mime;
            $a['ext'] = $ext;
            return $a;
        } else {
            return false;
        }
    }

    public function addFileMultiple($file_name, $type)
    {

        $info = getimagesize($file_name['tmp_name']);

        $path = $this->createFile($file_name, $type);

        //mime type
        $ext = pathinfo($file_name['name'], PATHINFO_EXTENSION);

        if ($ext == 'pdf') {
            $mime = "application/pdf";
        } else {
            $mime = $info['mime'];
        }

        if ($path != false) {
            $a = array();
            $a['type'] = $type;
            $a['path'] = $path;
            $a['mime'] = $mime;
            $a['ext'] = $ext;
            return $a;
        } else {
            return false;
        }
    }

    public function reArrayFiles($file)
    {
        $file_ary = array();
        $file_count = count($file['name']);
        $file_key = array_keys($file);

        for ($i = 0; $i < $file_count; $i++) {
            foreach ($file_key as $val) {
                $file_ary[$i][$val] = $file[$val][$i];
            }
        }
        return $file_ary;
    }

    public function createFile($file, $type)
    {

        if (is_array($file)) {
            $errors = array();
            $file_tmp = $file['tmp_name'];
            $file_type = filetype($file_tmp);
            $file_name = $file['name'];
            $t = explode('.', $file_name);
            $file_ext = strtolower(end($t));

            //new file name

            $new_file_name = $t[0] . '_' . $this->generateRandomString() . '.' . $file_ext;

            $extensions = array("jpeg", "jpg", "png", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx");

            if (in_array($file_ext, $extensions) === false) {
                $errors[] = "extension not allowed, please choose file.";
            }

            if (filesize($file_tmp) > 10485760) {
                $errors[] = 'File size must be less than 10 MB';
            }

            if (!is_dir(__DIR__ . '/uploads/' . $type)) {
                mkdir(__DIR__ . '/uploads/' . $type, 0755, true);
            }
            $path = __DIR__ . '/uploads/' . $type . '/' . $new_file_name;

            if (empty($errors) == true) {
                if (move_uploaded_file($file_tmp, $path)) {
                    return $new_file_name;
                }
            } else {
                return false;
            }
        }
    }

    public function generateRandomString($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function getFile($dp, $cv)
    {

        $b = array();
        if (is_array($dp) && sizeof($dp) > 0) {
            foreach ($dp as $d) {
                $a = array();
                $a['type'] = $d['type'];
                $a['mime'] = $d['mime'];
                $a['data'] = $this->getBase64Data($d['type'] . '/' . $d['path']);
            }
            array_push($b, $a);
        }

        $ee = array();

        if (is_array($cv) && sizeof($cv) > 0) {
            foreach ($cv as $c) {
                $a = array();
                $a['type'] = $c['type'];
                $a['mime'] = $c['mime'];
                $a['data'] = $this->getBase64Data($c['type'] . '/' . $c['path']);
                array_push($ee, $a);
            }

            array_push($b, $ee);
        }
        return $b;
    }

    public function getFileSingle($body)
    {

        $a = array();
        $a['type'] = $body['type'];
        $a['mime'] = $body['mime'];
        $a['data'] = $this->getBase64Data($body['type'] . '/' . $body['path']);

        return $a;
    }

    public function getFileSingleAttendance($file_name)
    {

        $a = array();
        $type = 'ATTENDANCE';
        $a = $this->getBase64DataNew($type . '/' . $file_name);

        return $a;
    }

    public function getBase64Data($path)
    {
        $p = __DIR__ . '/uploads/' . $path;
        if (file_exists($p)) {
            $data = file_get_contents($p, FILE_USE_INCLUDE_PATH);
            $base64 = base64_encode($data);
            return $base64;
        }
    }

    public function getBase64DataNew($path)
    {
        $p = __DIR__ . '/uploads/' . $path;
        if (file_exists($p)) {
            $data = file_get_contents($p, FILE_USE_INCLUDE_PATH);
            //$base64 = base64_encode($data);
            return $data;
        }
    }
}


class Session
{
    public function getCurrentSession()
    {
        $year = date('Y');
        $flag = 0;

        $month = date('m');
        if ((int) $month < 7) {
            $flag = 1;
        } else {
            $flag = 2;
        }
        $output = $year . $flag;
        return $output;
    }
}

class StorePhoto
{
    public function setPhoto($photo, $folder_name)
    {
        if ($photo != '') {
            if (!is_dir(__DIR__ . '/uploads/' . $folder_name)) {
                mkdir(__DIR__ . '/uploads/' . $folder_name, 0755, true);
            }

            $fu = new FileUpload();
            $gs = $fu->generateRandomString();

            $file_name = $gs . '_' . $photo['time_stamp'];
            file_put_contents(__DIR__ . '/uploads/' . $folder_name . '/' . $file_name, $photo['photo']);

            $b['file_name'] = $file_name;
            $b['time_stamp'] = $photo['time_stamp'];

            return $b;
        }
    }
}
