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

require_once APPPATH . '/../vendor/autoload.php';

use League\OAuth2\Client\Provider\GenericProvider;

use Webklex\PHPIMAP\ClientManager;


class Callback extends CI_Controller
{
    //private $tableArr = array();
    function __construct()
    {
        parent::__construct();
        //$this->table = new Table();
        //$this->tableArr = $this->table;
        $this->load->model('Master_Model');
    }

    function redirect()
    {
        if (isset($_GET['state'])) {
            $state = json_decode($_GET['state'], true);
            $email_id = $state['id'];
            $client_id = $state['client_id'];
            $agent_id = $state['agent_id'];
            $formType = 'EMAIL_ACCOUNT';
            $type = "incoming";
        }
        $getData = $this->Master_Model->getTokenAndRefreshToken($email_id, 'tms_email_account');
        $clientId = $getData['client_oauth2_id'];
        $clientSecret = $getData['client_secret'];
        $redirectUri = 'http://localhost/tms_v2.0/api/Callback/redirect';
        $tenant = $getData['tenant_id'];

        $provider = new GenericProvider([
            'clientId'                => $clientId,
            'clientSecret'            => $clientSecret,
            'redirectUri'             => $redirectUri,
            'urlAuthorize'            => "https://login.microsoftonline.com/$tenant/oauth2/v2.0/authorize",
            'urlAccessToken'          => "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token",
            'urlResourceOwnerDetails' => '',
            'scopes'                  => 'https://outlook.office365.com/IMAP.AccessAsUser.All offline_access'
        ]);

        if (!isset($_GET['code'])) {
            $authorizationUrl = $provider->getAuthorizationUrl();
            redirect($authorizationUrl);
        } else {
            try {
                $accessToken = $provider->getAccessToken('authorization_code', [
                    'code' => $_GET['code']
                ]);

                if ($accessToken->getRefreshToken()) {
                    $refreshToken = $accessToken->getRefreshToken();
                }
                $res = $this->Master_Model->saveTokenForEmail($accessToken->getToken(), $refreshToken, $email_id);
                if ($res) {
                    $cm = new ClientManager();

                    $client = $cm->make([
                        'host'          => 'outlook.office365.com',
                        'port'          => 993,
                        'encryption'    => 'ssl',
                        'validate_cert' => false,
                        'username'      => $getData['incoming_user_name'],
                        'password'      => $accessToken->getToken(),
                        'protocol'      => 'imap',
                        'authentication' => 'oauth'
                    ]);
                    if ($client->connect()) {
                        // $folder = $client->getFolder('INBOX');
                        // $messages = $folder->query()->all()->get();
                        $message = 'IMAP connection successful.';
                        $res = $this->Master_Model->saveTestCongifOfMail($email_id, $client_id, $agent_id, $formType, $type, $message, $getData['incoming_user_name'], 'true');
                        $this->displayMessage($message, true);
                        return;
                    } else {
                        $message = 'IMAP connection failed';
                        $res = $this->Master_Model->saveTestCongifOfMail($email_id, $client_id, $agent_id, $formType, $type, $message, $getData['incoming_user_name'], 'false');
                        $this->displayMessage($message, false);
                        return;
                    }
                }
            } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
                exit('Failed to get access token: ' . $e->getMessage());
            }
        }
    }

    private function displayMessage($message, $isSuccess)
    {
        $color = $isSuccess ? 'green' : 'red'; // Green for success, red for failure
        $message .= " move back to previous page and refresh it";
        echo "
        <html>
        <head>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f4f4f4;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100vh;
                    margin: 0;
                }
                .message-box {
                    padding: 20px;
                    border-radius: 5px;
                    background-color: white;
                    box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);
                    text-align: center;
                }
                .message-box p {
                    font-size: 16px;
                    color: $color;
                }
            </style>
        </head>
        <body>
            <div class='message-box'>
                <p>{$message}</p>
            </div>
        </body>
        </html>
        ";
    }
}
