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

class Docusign extends CI_Controller {
    private $client_id = '69216299cb9bd0b1eda1d7e3b02fba9a'; // Your DocuSign Integration Key
    private $client_secret = '95a26d9c171023826d2092991e925a45';
    private $redirect_uri = 'http://localhost/perfex_crm/Docusign/callback'; // Redirect URI
    private $api_key = '90df7a46894b557453a582ac80070c5817cc2483d29dd37db25da87059009680'; // Your API Key
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
    }
    public function index($id = '')
    {
        echo 'here';
    }
    public function login() {
        $auth_url = "https://account.docusign.com/oauth/auth?" . http_build_query([
            "response_type" => "code",
            "scope" => "signature extended",
            "client_id" => $this->client_id,
            "redirect_uri" => $this->redirect_uri
        ]);
        redirect($auth_url);
    }
    public function callback() {
        if (!isset($_GET['code'])) {
            exit('Authorization code not received.');
        }
    
        $code = $_GET['code'];
        $url = "https://account.docusign.com/oauth/token";
        
        $headers = [
            "Authorization: Basic " . base64_encode($this->client_id . ":" . $this->client_secret),
            "Content-Type: application/x-www-form-urlencoded"
        ];
    
        $data = [
            "grant_type" => "authorization_code",
            "code" => $code,
            "redirect_uri" => $this->redirect_uri
        ];
    
        $response = $this->send_request($url, $headers, $data);
        
        if (isset($response->access_token)) {
            // Store tokens in session or database
            $this->session->set_userdata('docusign_access_token', $response->access_token);
            $this->session->set_userdata('docusign_refresh_token', $response->refresh_token);
            echo "Login successful. You can now send documents!";
        } else {
            echo "Failed to get access token.";
        }
    }

    public function refresh_token() {
        $refresh_token = $this->session->userdata('docusign_refresh_token');
        if (!$refresh_token) exit('No refresh token available.');
    
        $url = "https://account.docusign.com/oauth/token";
        
        $headers = [
            "Authorization: Basic " . base64_encode($this->client_id . ":" . $this->client_secret),
            "Content-Type: application/x-www-form-urlencoded"
        ];
    
        $data = [
            "grant_type" => "refresh_token",
            "refresh_token" => $refresh_token
        ];
    
        $response = $this->send_request($url, $headers, $data);
    
        if (isset($response->access_token)) {
            $this->session->set_userdata('docusign_access_token', $response->access_token);
            echo "Token refreshed successfully!";
        } else {
            echo "Failed to refresh token.";
        }
    }

    public function send_document() {
        $access_token = $this->session->userdata('docusign_access_token');
        if (!$access_token) exit('You need to log in first.');
    
        $url = "https://demo.docusign.net/restapi/v2.1/accounts/YOUR_ACCOUNT_ID/envelopes";
    
        $headers = [
            "Authorization: Bearer " . $access_token,
            "Content-Type: application/json"
        ];
    
        $data = [
            "templateId" => "YOUR_TEMPLATE_ID",
            "templateRoles" => [
                [
                    "email" => "recipient@example.com",
                    "name" => "John Doe",
                    "roleName" => "Signer",
                    "tabs" => [
                        "textTabs" => [
                            [
                                "tabLabel" => "CustomField",
                                "value" => "Custom Value"
                            ]
                        ]
                    ]
                ]
            ],
            "status" => "sent"
        ];
    
        $response = $this->send_request($url, $headers, json_encode($data));
        
        if (isset($response->envelopeId)) {
            echo "Document sent successfully!";
        } else {
            echo "Failed to send document.";
        }
    }

    private function send_request($url, $headers, $data) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data);
    
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response);
    }
    
}
?>
