<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class DocusignApi extends ResourceController
{
    protected $format = 'json';
    
    private string $integrationKey;
    private string $userId;
    private string $accountId;
    private string $basePath;
    private string $oauthBasePath;

    public function __construct()
    {
		$db = \Config\Database::connect();
        // $docusign_user_id = 'c85fb4fd-b612-4361-a16b-20022e02f667';
        $docusign_account_id = '23655fac-fbe7-4230-9076-c3f51bd2a322';
        // $docusign_integration_key = 'a2089074-ed1a-43a7-a447-b01ef6a1a9c9';
        $docusign_account_base_uri = 'https://demo.docusign.net';
        // $docusign_oauth_base_path = 'https://account-d.docusign.com';

        // $this->integrationKey = $docusign_integration_key;
        // $this->userId = $docusign_user_id;
        $this->accountId = $docusign_account_id;
        $this->basePath = $docusign_account_base_uri . '/restapi';
        // $this->oauthBasePath = $docusign_oauth_base_path;

        // Environment setup
        // $environment = getenv('DOCUSIGN_ENVIRONMENT') ?: 'sandbox';
        
        // if ($environment === 'production') {
        //     $this->basePath = 'https://na3.docusign.net/restapi';
        //     $this->oauthBasePath = 'https://account.docusign.com';
        // } else {
        //     $this->basePath = 'https://demo.docusign.net/restapi';
        //     $this->oauthBasePath = 'https://account-d.docusign.com';
        // }
    }

    // /**
    //  * API Endpoint: Get JWT Access Token
    //  * GET /docusign-api/token
    //  */
    // public function token()
    // {
    //     try {
    //         $accessToken = $this->getJwtAccessToken();
            
    //         if (!$accessToken) {
    //             return $this->fail('Failed to obtain access token', 500);
    //         }

    //         return $this->respond([
    //             'success' => true,
    //             'access_token' => $accessToken,
    //             'token_type' => 'Bearer',
    //             'expires_in' => 3600,
    //             'account_id' => $this->accountId
    //         ]);

    //     } catch (\Exception $e) {
    //         log_message('error', 'DocuSign JWT Token Error: ' . $e->getMessage());
    //         return $this->fail($e->getMessage(), 500);
    //     }
    // }

    /**
     * API Endpoint: Send Envelope with Prepared PDF File
     * POST /docusign-api/send-envelope-prepared
     * 
     * Request Body:
     * {
     *   "signers": [
     *     {
     *       "email": "customer1@example.com",
     *       "name": "John Doe",
     *       "anchor_string": "/sn1/"  // Optional: text in PDF to anchor signature
     *     },
     *     {
     *       "email": "customer2@example.com",
     *       "name": "Jane Smith",
     *       "anchor_string": "/sn2/"  // Optional
     *     }
     *   ],
     *   "pdf_file_path": "contracts/template.pdf",
     *   "email_subject": "Please sign this document",
     *   "use_anchor_tags": true  // Set to false to use absolute positioning
     * }
     */
    public function sendEnvelopePrepared()
    {
        try {
            // Get request data
            /** @var \CodeIgniter\HTTP\IncomingRequest $request */
            $request = $this->request;
            $data = $request->getJSON(true);
            $db = \Config\Database::connect();

            $prefered_branch = $data['prefered_branch'];
            if (!$prefered_branch) {
                return $this->fail('Prefered branch is required', 400);
            }

            
            $branch_result = $db->table('epos_branches')->where('site_name', $prefered_branch)->get()->getRow();
            if (!$branch_result) {
                return $this->fail('Branch not found', 404);
            }
            $prefered_branch_id = $branch_result->id;

            $result = (object) \App\Models\BranchConfig::getAll($prefered_branch_id);
            if (empty($result->docusign_user_id)) {
                return $this->fail('Prefered branch not found', 404);
            }
            $docusign_company_signer_name  = $result->docusign_company_signer_name  ?? '';
            $docusign_company_signer_email = $result->docusign_company_signer_email ?? '';
            $integrationKey                = $result->docusign_integration_key      ?? '';
            $userId                        = $result->docusign_user_id              ?? '';
            $oauthBasePath                 = $result->docusign_oauth_base_path      ?? '';
            $basePath                      = ($result->docusign_account_base_uri    ?? '') . '/restapi';
            $docusign_account_id           = $result->docusign_account_id           ?? '';

            // Validate required fields
            if (empty($data['signers']) || !is_array($data['signers'])) {
                return $this->fail("signers must be a non-empty array", 400);
            }

            if (empty($data['pdf_file_path'])) {
                return $this->fail("pdf_file_path is required", 400);
            }

            // Validate each signer
            foreach ($data['signers'] as $index => $signer) {
                if (empty($signer['email']) || empty($signer['name'])) {
                    return $this->fail("Signer at index {$index} is missing email or name", 400);
                }
            }

            // New signer to append
            $newSigner = [
                "email" => $docusign_company_signer_email,
                "name" => $docusign_company_signer_name,
                "full_name_anchor_string" => "/fn2/",
                "signed_anchor_string" => "/sn2/",
                "date_signed_anchor_string" => "/dt2/"
            ];

            $data['signers'][] = $newSigner;
            
            // Build HTML for PDF
            $pdfPath = $data['pdf_file_path'];
            if (!$pdfPath) {
                $pdfPath = "orderuk-contract.pdf";
            }

            // $result = $db->table('epos_app_config')->where('key' , 'customer_register_email_subject')->get()->getRow();
            // $mail_subject = $result->value ?? "New Account Application Request";

            // $data['email_subject'] = $mail_subject;
            $data['email_subject'] = "New Account Application Form";
            $html_content = $this->build_pdf_html_content($data);

            // Generate PDF
            // Note: This requires DomPDF library - install via: composer require dompdf/dompdf
            // For now, we'll create the PDF file directly using DomPDF if available

            // Check if DomPDF is available
            if (class_exists('\Dompdf\Dompdf')) {
                $dompdf = new \Dompdf\Dompdf();
                $dompdf->loadHtml($html_content);
                $dompdf->setPaper('A4', 'Portrait');
                // $dompdf->set_option('margin-left', '10mm');
                $dompdf->set_option('margin-right', '10mm');
                $dompdf->set_option('margin-top', '10mm');
                $dompdf->set_option('margin-bottom', '10mm');
                $dompdf->render();
                $pdf_content = $dompdf->output();
            } else {
                // Fallback: Return error if DomPDF is not installed
                return response()->setJSON([
                    'success' => 0,
                    'msg' => 'PDF library not installed. Please install DomPDF: composer require dompdf/dompdf'
                ]);
            }
            
            // $pdf_content = file_get_contents(WRITEPATH . 'uploads/contract_template.pdf');


            // Read and encode PDF
            $documentBase64 = base64_encode($pdf_content);
            $documentName = basename($pdfPath);

            // Get access token
            $accessToken = $this->getJwtAccessToken($integrationKey, $userId, $oauthBasePath);
            
            if (!$accessToken) {
                return $this->fail('Failed to obtain access token', 500);
            }

            // Determine if using anchor tags or absolute positioning
            $useAnchorTags = $data['use_anchor_tags'] ?? true;

            // Prepare signers with routing order
            $signers = [];
            foreach ($data['signers'] as $index => $signer) {
                $recipientId = (string)($index + 1);
                $routingOrder = (string)($index + 1);
                
                // Build tabs based on positioning method
                $tabs = [];
                
                if ($useAnchorTags && 
                !empty($signer['signed_anchor_string']) &&
                !empty($signer['date_signed_anchor_string'])) {
                    // Use anchor string positioning (recommended for prepared PDFs)
                    $tabs['fullNameTabs'] = [
                        [
                            "anchorString"=> $signer['full_name_anchor_string'],
                            "anchorUnits"=> "pixels",
                            "anchorXOffset"=> "0",
                            "anchorYOffset"=> "0",
                            "font"=> "Tahoma",
                            "fontColor"=> "Purple",
                            "tabLabel"=> "FullNameLabel"
                        ]
                    ];
                    $tabs['signHereTabs'] = [
                        [
                            'anchorString' => $signer['signed_anchor_string'],
                            'anchorUnits' => 'pixels',
                            'anchorXOffset' => '0',
                            'anchorYOffset' => '0',
                        ]
                    ];
                    $tabs['dateSignedTabs'] = [
                        [
                            'anchorString' => $signer['date_signed_anchor_string'],
                            'anchorUnits' => 'pixels',
                            'anchorXOffset' => '0',
                            'anchorYOffset' => '0',
                            'tabLabel' => 'Date Signed',
                        ]
                    ];
                    if ($index == 0) {
                        $tabs['signerAttachmentTabs'] = [
                            [
                                'anchorString' => $signer['attachment_anchor_string1'],
                                'anchorUnits' => 'pixels',
                                'anchorXOffset' => '0',
                                'anchorYOffset' => '0',
                                'tabLabel' => 'Upload supporting document1',
                                'required' => 'true',
                            ],
                            [
                                'anchorString' => $signer['attachment_anchor_string2'],
                                'anchorUnits' => 'pixels',
                                'anchorXOffset' => '0',
                                'anchorYOffset' => '0',
                                'tabLabel' => 'Upload supporting document2',
                                'required' => 'true',
                            ]
                        ];
                    }
                } else {
                    // Use absolute positioning (fallback)
                    $pageNumber = $signer['page_number'] ?? '1';
                    $xPosition = $signer['x_position'] ?? '100';
                    $yPosition = $signer['y_position'] ?? (string)(100 + ($index * 100));
                    
                    $tabs['signHereTabs'] = [
                        [
                            'documentId' => '1',
                            'pageNumber' => $pageNumber,
                            'xPosition' => $xPosition,
                            'yPosition' => $yPosition
                        ]
                    ];
                    $tabs['dateSignedTabs'] = [
                        [
                            'documentId' => '1',
                            'pageNumber' => $pageNumber,
                            'xPosition' => (string)((int)$xPosition + 200),
                            'yPosition' => $yPosition
                        ]
                    ];
                }
                
                $signers[] = [
                    'email' => $signer['email'],
                    'name' => $signer['name'],
                    'recipientId' => $recipientId,
                    'routingOrder' => $routingOrder,
                    'tabs' => $tabs
                ];
            }

            // Prepare envelope data
            $envelopeData = [
                'emailSubject' => $data['email_subject'] ?? 'Please sign this document',
                'documents' => [
                    [
                        'documentBase64' => $documentBase64,
                        'name' => $documentName,
                        'fileExtension' => 'pdf',
                        'documentId' => '1'
                    ]
                ],
                'recipients' => [
                    'signers' => $signers
                ],
                'status' => 'sent'
            ];

            // Send envelope via DocuSign API
            $result = $this->createEnvelope($accessToken, $envelopeData, $basePath, $docusign_account_id);

            if ($result['envelopeId']) {
                $db = \Config\Database::connect();
                $db->table('epos_customer_registration')->where('id', $data['registration_id'])->update(['envelope_id' => $result['envelopeId']]);

                return $this->respond([
                    'success' => true,
                    // 'envelope_id' => $result['envelopeId'],
                    // 'status' => $result['status'],
                    // 'status_date_time' => $result['statusDateTime'] ?? null,
                    // 'signers_count' => count($signers),
                    // 'document_used' => $documentName,
                    // 'positioning_method' => $useAnchorTags ? 'anchor_tags' : 'absolute',
                    // 'message' => 'Envelope sent successfully to ' . count($signers) . ' signer(s)'
                ]);
            } else {
                return $this->respond([
                    'success' => false,
                    'msg' => $result['message']
                ]);
            }

        } catch (\Exception $e) {
            log_message('error', 'DocuSign Send Envelope Prepared Error: ' . $e->getMessage());
            return $this->fail($e->getMessage(), 500);
        }
    }

    /**
     * API Endpoint: Resend/Create DocuSign Envelope for Registration
     * POST /docusign-api/resend-envelope/{registrationId}
     * 
     * Creates a new DocuSign envelope for a customer registration
     * 
     * @param string $registrationId
     */
    public function resendEnvelope($registrationId = null)
    {
        $db = \Config\Database::connect();
        $branch = session()->get('branch');
        // Branch config via the key-value table.
        $branchConfig = (object) \App\Models\BranchConfig::getAll($branch, session()->get('organization_id'));
        $docusign_user_id              = $branchConfig->docusign_user_id              ?? '';
        $docusign_integration_key      = $branchConfig->docusign_integration_key      ?? '';
        $docusign_oauth_base_path      = $branchConfig->docusign_oauth_base_path      ?? '';
        $docusign_company_signer_name  = $branchConfig->docusign_company_signer_name  ?? '';
        $docusign_company_signer_email = $branchConfig->docusign_company_signer_email ?? '';
        $docusign_account_id           = $branchConfig->docusign_account_id           ?? '';
        $docusign_account_base_uri     = $branchConfig->docusign_account_base_uri     ?? '';
        $basePath                      = $docusign_account_base_uri . '/restapi';

        try {
            if (!$registrationId) {
                return $this->fail('Registration ID is required', 400);
            }

            $db = \Config\Database::connect();
            
            // Get registration data
            $registration = $db->table('epos_customer_registration')
                ->where('id', $registrationId)
                ->get()
                ->getRowArray();

            if (!$registration) {
                return $this->fail('Registration not found', 404);
            }

            // Build signers array from registration data
            $signers = [
                [
                    "email" => $registration['contact_email'],
                    "name" => $registration['business_legal_name'],
                    "full_name_anchor_string" => "/fn1/",
                    "signed_anchor_string" => "/sn1/",
                    "date_signed_anchor_string" => "/dt1/",
                    "attachment_anchor_string1" => "/pat1/",
                    "attachment_anchor_string2" => "/bat1/"
                ]
            ];

            
            $newSigner = [
                "email" => $docusign_company_signer_email,
                "name" => $docusign_company_signer_name,
                "full_name_anchor_string" => "/fn2/",
                "signed_anchor_string" => "/sn2/",
                "date_signed_anchor_string" => "/dt2/"
            ];

            $signers[] = $newSigner;

            // Get email subject from config
            // $result = $db->table('epos_app_config')->where('key', 'customer_register_email_subject')->get()->getRow();
            // $email_subject = $result->value ?? "Please sign this contract";
            $email_subject = "New Account Application Form";

            // Prepare data array for PDF generation
            $data = [
                'registration_id' => $registrationId,
                'signers' => $signers,
                'email_subject' => $email_subject,
                'use_anchor_tags' => true,
                'pdf_file_path' => 'orderuk-contract.pdf',
                'busi_legal_nm' => $registration['business_legal_name'],
                'busi_trad_nm' => $registration['business_trading_name'],
                'busi_start_dt' => $registration['business_start_date'],
                'addr_line1' => $registration['address_line1'],
                'addr_line2' => $registration['address_line2'],
                'county' => $registration['county'],
                'city' => $registration['city'],
                'country' => $registration['country'],
                'post_code' => $registration['post_code'],
                'contact_nm' => $registration['contact_name'],
                'contact_phone_ll' => $registration['contact_telephone_landline'],
                'contact_phone_mb' => $registration['contact_telephone_mobile'],
                'contact_email' => $registration['contact_email'],
                'company_no' => $registration['company_number'],
                'vat_number' => $registration['vat_number'],
                'busi_trad_years' => $registration['business_trading_years'],
                'store_sz' => $registration['store_size'],
                'store_avg' => $registration['store_average'],
                'pref_payment_method' => $registration['prefered_payment_method'],
                'credit_acc_facility' => $registration['credit_account_facility'],
                'offers_and_info' => $registration['offers_and_info'],
                'self_service' => $registration['self_service'],
                'click_and_collect' => $registration['click_and_collect'],
                'delivered' => $registration['delivered'],
                'confirm_legal_owner_director' => $registration['confirm_legal_owner_director'],
                'prefered_branch' => $registration['prefered_branch'],
                'sell_alcohol' => $registration['sell_alcohol'],
                'sell_tobacco' => $registration['sell_tobacco'],
                'sell_vapes' => $registration['sell_vapes'],
                'premises_licence' => $registration['premises_licence'],
                'eoid' => $registration['eoid'],
                'fid' => $registration['fid'],
                'owner_house_no'   => $registration['contact_addr_house_number']    ?? '',
                'owner_house_name' => $registration['contact_addr_house_name_flat'] ?? '',
                'owner_street'     => $registration['contact_addr_street']          ?? '',
                'owner_village'    => $registration['contact_addr_vill_town']       ?? '',
                'owner_city'       => $registration['contact_addr_city']            ?? '',
                'owner_country'    => $registration['contact_addr_country']         ?? '',
                'owner_post_code'  => $registration['contact_addr_postcode']        ?? '',
                'credit_limit'     => $registration['requested_credit_limit']       ?? 0,
            ];

            // Format payment method
            $pref_payment_method = $registration['prefered_payment_method'] ?? '';
            if ($pref_payment_method == "cash") {
                $pref_payment_method = "Cash";
            } else if ($pref_payment_method == "bank_transfer") {
                $pref_payment_method = "Bank Transfer";
            } else if ($pref_payment_method == "echo_pay") {
                $pref_payment_method = "EchoPay";
            } else if ($pref_payment_method == "card") {
                $pref_payment_method = "Card";
            } else if ($pref_payment_method == "credit_facility") {
                $pref_payment_method = "Credit Facility";
            }
            $data['pref_payment_method'] = $pref_payment_method;

            // Build HTML for PDF
            $pdfPath = $data['pdf_file_path'];
            if (!$pdfPath) {
                $pdfPath = "orderuk-contract.pdf";
            }

            $data['email_subject'] = $email_subject;
            $html_content = $this->build_pdf_html_content($data);

            // Generate PDF
            if (class_exists('\Dompdf\Dompdf')) {
                $dompdf = new \Dompdf\Dompdf();
                $dompdf->loadHtml($html_content);
                $dompdf->setPaper('A4', 'Portrait');
                // $dompdf->set_option('margin-left', '10mm');
                $dompdf->set_option('margin-right', '10mm');
                $dompdf->set_option('margin-top', '10mm');
                $dompdf->set_option('margin-bottom', '10mm');
                $dompdf->render();
                $pdf_content = $dompdf->output();
            } else {
                return $this->fail('PDF library not installed', 500);
            }

            // Read and encode PDF
            $documentBase64 = base64_encode($pdf_content);
            $documentName = basename($pdfPath);

            // Get access token
            $accessToken = $this->getJwtAccessToken($docusign_integration_key, $docusign_user_id, $docusign_oauth_base_path);
            
            if (!$accessToken) {
                return $this->fail('Failed to obtain access token', 500);
            }

            // Build signers array for DocuSign API
            $useAnchorTags = $data['use_anchor_tags'] ?? true;
            $docusignSigners = [];
            
            foreach ($signers as $index => $signer) {
                $recipientId = (string)($index + 1);
                $routingOrder = (string)($index + 1);
                $tabs = [];

                if ($useAnchorTags && 
                    !empty($signer['signed_anchor_string']) &&
                    !empty($signer['date_signed_anchor_string'])) {
                    // Use anchor string positioning
                    $tabs['fullNameTabs'] = [
                        [
                            "anchorString"=> $signer['full_name_anchor_string'] ?? '/fn' . $recipientId . '/',
                            "anchorUnits"=> "pixels",
                            "anchorXOffset"=> "0",
                            "anchorYOffset"=> "0",
                            "font"=> "Tahoma",
                            "fontColor"=> "Purple",
                            "tabLabel"=> "FullNameLabel"
                        ]
                    ];
                    $tabs['signHereTabs'] = [
                        [
                            'anchorString' => $signer['signed_anchor_string'],
                            'anchorUnits' => 'pixels',
                            'anchorXOffset' => '0',
                            'anchorYOffset' => '0',
                        ]
                    ];
                    $tabs['dateSignedTabs'] = [
                        [
                            'anchorString' => $signer['date_signed_anchor_string'],
                            'anchorUnits' => 'pixels',
                            'anchorXOffset' => '0',
                            'anchorYOffset' => '0',
                            'tabLabel' => 'Date Signed',
                        ]
                    ];
                    // Add attachment tabs for first signer
                    if ($index == 0 && !empty($signer['attachment_anchor_string1']) && !empty($signer['attachment_anchor_string2'])) {
                        $tabs['signerAttachmentTabs'] = [
                            [
                                'anchorString' => $signer['attachment_anchor_string1'],
                                'anchorUnits' => 'pixels',
                                'anchorXOffset' => '0',
                                'anchorYOffset' => '0',
                                'tabLabel' => 'Upload supporting document1',
                                'required' => 'true',
                            ],
                            [
                                'anchorString' => $signer['attachment_anchor_string2'],
                                'anchorUnits' => 'pixels',
                                'anchorXOffset' => '0',
                                'anchorYOffset' => '0',
                                'tabLabel' => 'Upload supporting document2',
                                'required' => 'true',
                            ]
                        ];
                    }
                } else {
                    // Use absolute positioning (fallback)
                    $pageNumber = '1';
                    $xPosition = '100';
                    $yPosition = (string)(100 + ($index * 100));
                    
                    $tabs['signHereTabs'] = [
                        [
                            'documentId' => '1',
                            'pageNumber' => $pageNumber,
                            'xPosition' => $xPosition,
                            'yPosition' => $yPosition
                        ]
                    ];
                    $tabs['dateSignedTabs'] = [
                        [
                            'documentId' => '1',
                            'pageNumber' => $pageNumber,
                            'xPosition' => (string)((int)$xPosition + 200),
                            'yPosition' => $yPosition
                        ]
                    ];
                }
                
                $docusignSigners[] = [
                    'email' => $signer['email'],
                    'name' => $signer['name'],
                    'recipientId' => $recipientId,
                    'routingOrder' => $routingOrder,
                    'tabs' => $tabs
                ];
            }

            // Prepare envelope data
            $envelopeData = [
                'emailSubject' => $email_subject,
                'documents' => [
                    [
                        'documentBase64' => $documentBase64,
                        'name' => $documentName,
                        'fileExtension' => 'pdf',
                        'documentId' => '1'
                    ]
                ],
                'recipients' => [
                    'signers' => $docusignSigners
                ],
                'status' => 'sent'
            ];

            // Send envelope via DocuSign API
            $result = $this->createEnvelope($accessToken, $envelopeData, $basePath, $docusign_account_id);

            if ($result['envelopeId']) {
                $db->table('epos_customer_registration')->where('id', $registrationId)->update(['envelope_id' => $result['envelopeId']]);

                return $this->respond([
                    'success' => true,
                    'envelope_id' => $result['envelopeId']
                ]);
            } else {
                return $this->respond([
                    'success' => false,
                    'msg' => $result['message'] ?? 'Failed to create envelope',
                    'result' => $result
                ]);
            }

        } catch (\Exception $e) {
            log_message('error', 'DocuSign Resend Envelope Error: ' . $e->getMessage());
            return $this->respond([
                'success' => false,
                'msg' => $e->getMessage(),
                'result' => [
                    'message' => $e->getMessage(),
                    'code' => $e->getCode(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                    'trace' => $e->getTraceAsString()
                ]
            ]);
            // return $this->fail($e->getMessage(), 500);
        }
    }

    public function build_pdf_html_content($data)
	{
		$html = '<!DOCTYPE html>
			<html>
				<head>
					<meta charset="UTF-8">
					<style id="style-for-docusign"></style>
				</head>

				<body>
                    
                    
                    <p>Wholesale terms and conditions (T&Cs) are critical for 2026 business operations to define the financial and legal relationship between a supplier and a retail buyer. Below are the fundamental clauses for a basic wholesale agreement. </p>
                    
                    <h2>1. Ordering and Minimums</h2>
                        <ul>
                        <li>Minimum Order Quantity (MOQ): Specify the minimum number of units or the Minimum Order Value (MOV), often ranging from $300 to $600 for first-time buyers.</li>
                        <li>Ordering Process: Detail how orders must be submitted (e.g., via a wholesale portal, email, or phone) and how confirmation is provided.</li> 
                        </ul>

                    <h2>2. Pricing and Payments</h2>
                        <ul>
                        <li>Wholesale Pricing: State that prices are subject to change without notice and clarify if they are listed in a specific currency (e.g., USD).</li> 
                        <li>MSRP Policy: Define the Manufacturer\'s Suggested Retail Price (MSRP) and any restrictions on discounting (e.g., no more than 15% off).</li> 
                        <li>Payment Terms: Clarify if payment is Proforma (upfront before shipping) or Net Terms (e.g., Net 30, due 30 days after delivery).</li> 
                        <li>Accepted Methods: List permitted payment types, such as bank transfer (EFT), credit card, or check. </li> 
                        </ul>

                    <h2>3. Shipping and Delivery</h2>
                        <ul>
                        <li>Costs and Carriers: State who pays for shipping (usually the buyer) and the methods available.</li> 
                        <li>Risk and Title: Specify that ownership and risk of loss pass to the buyer once the goods are picked up by the carrier.</li> 
                        <li>Estimated Timelines: Provide typical processing times while noting that delivery dates are estimates, not guarantees. </li> 
                        </ul>

                    <h2>4. Returns and Damages</h2>
                        <ul>
                        <li>Reporting Window: Set a strict timeframe (e.g., 7–14 days after delivery) for reporting damaged or missing items.</li> 
                        <li>Restocking Fees: Define fees for "unsuitable" returns, often around 15% plus shipping costs.</li> 
                        <li>Return Authorization: Explicitly state that no returns are accepted without prior written approval. </li> 
                        </ul>

                    <h2>5. Legal Protections</h2>
                        <ul>
                        <li>Limitation of Liability: Limit the seller\'s liability for indirect or consequential damages and cap total damages at the order value.</li> 
                        <li>Retention of Title: Clause allowing the seller to retain legal ownership of goods until they are paid for in full.</li> 
                        <li>Governing Law: Identify the specific jurisdiction (e.g., state or country) whose laws will govern the agreement. </li> 
                        <li>For standard templates, you can consult resources like the LegalZebra Wholesale Template or Simplisales eCommerce Guides. </li> 
                        </ul>
                                
                    <table style="width: 100%;">
                        <tr>
                            <td style="width: 50%;">
                                <p>Please sign the document</p>
                                <div>Name: <span style="color: white;">/fn1/</span></div>
                                <br>
                                <br>
                                <div>Signed: <span style="color: white;">/sn1/</span></div>
                                <br>
                                <br>
                                <div>Date: <span style="color: white;">/dt1/</span></div>
                                <br>
                                <br>
                                <div>Personal ID: <span style="color: white;">/pat1/</span></div>
                                <br>
                                <br>
                                <br>
                                <br>
                                <div>Business ID: <span style="color: white;">/bat1/</span></div>
                            </td>
                            <td style="width: 50%; vertical-align: top;">
                                <p>Please sign the document</p>
                                <div>Name: <span style="color: white;">/fn2/</span></div>
                                <br>
                                <br>
                                <div>Signed: <span style="color: white;">/sn2/</span></div>
                                <br>
                                <br>
                                <div>Date: <span style="color: white;">/dt2/</span></div>
                            </td>
                        </tr>
                    </table>

				</body>
			</html>';

        $template_html = '';
        // Read template file content
		$templatePath = WRITEPATH . 'docusign/template.html';
		if (!file_exists($templatePath)) {
			$template_html = $html;
		} else {
            $template_html = file_get_contents($templatePath);
        }

        $style_for_docusign = '<style>
                        body {
                            margin: 0;
                            padding: 0;
                            font-family: Arial, sans-serif;
                        }
                        .customer-register-panel-for-email {
                            width: 100%;
                            margin-left: 0mm;
                            margin-right: 10mm;
                            box-sizing: border-box;
                        }
                        .customer-register-panel-for-email table {
                            border-collapse: collapse;
                            width: 100%;
                            font-family: Arial, sans-serif;
                            font-size: 12px;
                            color: #545454;
                        }
                        .customer-register-panel-for-email th.section-title {
                            text-align: left;
                            background: #e5e5e5;
                            font-size: 14px;
                            padding: 4px 8px;
                            border: 1px solid #ccc;
                        }
                        .customer-register-panel-for-email td {
                            border: 1px solid #ccc;
                            padding: 4px 6px;
                            vertical-align: top;
                        }
                        .customer-register-panel-for-email td.label {
                            width: 22%;
                            white-space: nowrap;
                            font-weight: bold;
                        }
                        .customer-register-panel-for-email td.value input,
                        .customer-register-panel-for-email td.value select {
                            width: 100%;
                            box-sizing: border-box;
                        }
                        .customer-register-panel-for-email .checkbox-row label,
                        .customer-register-panel-for-email .checkbox-column label {
                            display: inline-block;
                            margin-right: 14px;
                        }
                        .customer-register-panel-for-email .checkbox-column label {
                            display: block;
                        }
                        .customer-register-panel-for-email .required::after {
                            content: \'(*)\';
                            color: #c00;
                            padding-left: 2px;
                        }
                    </style>';
		$customer_form_for_docusign = '<h1 style="text-align: center; font-size: 24px; font-weight: bold; margin-top: -10px;">'.$data['email_subject'].'</h1>
                    <div class="customer-register-panel-for-email">
                        <table class="email-table" cellpadding="4" cellspacing="0" style="width: 100%;">
                            <tr>
                                <th colspan="2" class="section-title">Business</th>
                            </tr>
                            <tr>
                                <td class="label required">Business Legal Name:</td>
                                <td class="value">'.$data['busi_legal_nm'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">Business Trading Name:</td>
                                <td class="value">'.$data['busi_trad_nm'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">Business Start Date:</td>
                                <td class="value">'.$data['busi_start_dt'].'</td>
                            </tr>
                            <tr>
                                <td class="label">Preferred Branch:</td>
                                <td class="value">'.$data['prefered_branch'].'</td>
                            </tr>
                            <tr>
                                <td colspan="2" class="checkbox-cell">
                                    <label>
                                    <input type="checkbox" id="confirm_legal_owner_director_for_email" checked="checked" />
                                    I confirm I am the Legal Owner or Director
                                    </label>
                                </td>
                            </tr>

                            <tr>
                                <th colspan="2" class="section-title">Address</th>
                            </tr>
                            <tr>
                                <td class="label required">Address Line 1:</td>
                                <td class="value">'.$data['addr_line1'].'</td>
                            </tr>
                            <tr>
                                <td class="label">Address Line 2:</td>
                                <td class="value">'.$data['addr_line2'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">County:</td>
                                <td class="value">'.$data['county'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">City:</td>
                                <td class="value">'.$data['city'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">Country:</td>
                                <td class="value">'.$data['country'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">Post Code:</td>
                                <td class="value">'.$data['post_code'].'</td>
                            </tr>

                            <tr>
                                <th colspan="2" class="section-title">Contact</th>
                            </tr>
                            <tr>
                                <td class="label required">Contact Name:</td>
                                <td class="value">'.$data['contact_nm'].'</td>
                            </tr>
                            <tr>
                                <td class="label">Contact Telephone Landline:</td>
                                <td class="value">'.$data['contact_phone_ll'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">Contact Telephone Mobile:</td>
                                <td class="value">'.$data['contact_phone_mb'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">Contact email address:</td>
                                <td class="value">'.$data['contact_email'].'</td>
                            </tr>

                            <tr>
                                <th colspan="2" class="section-title">Owner/Director Address</th>
                            </tr>
                            <tr>
                                <td class="label required">House Number:</td>
                                <td class="value">'.htmlspecialchars($data['owner_house_no'] ?? '').'</td>
                            </tr>
                            <tr>
                                <td class="label">House Name/Flat:</td>
                                <td class="value">'.htmlspecialchars($data['owner_house_name'] ?? '').'</td>
                            </tr>
                            <tr>
                                <td class="label required">Street:</td>
                                <td class="value">'.htmlspecialchars($data['owner_street'] ?? '').'</td>
                            </tr>
                            <tr>
                                <td class="label required">Village/Town:</td>
                                <td class="value">'.htmlspecialchars($data['owner_village'] ?? '').'</td>
                            </tr>
                            <tr>
                                <td class="label required">City:</td>
                                <td class="value">'.htmlspecialchars($data['owner_city'] ?? '').'</td>
                            </tr>
                            <tr>
                                <td class="label required">Country:</td>
                                <td class="value">'.htmlspecialchars($data['owner_country'] ?? '').'</td>
                            </tr>
                            <tr>
                                <td class="label required">Post Code:</td>
                                <td class="value">'.htmlspecialchars($data['owner_post_code'] ?? '').'</td>
                            </tr>

                            <tr>
                                <th colspan="2" class="section-title">Company</th>
                            </tr>
                            <tr>
                                <td class="label">Company Number:</td>
                                <td class="value">'.$data['company_no'].'</td>
                            </tr>
                            <tr>
                                <td class="label">VAT Number:</td>
                                <td class="value">'.$data['vat_number'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">For how many years has the business been trading?</td>
                                <td class="value">'.$data['busi_trad_years'].'</td>
                            </tr>

                            <tr>
                                <th colspan="2" class="section-title">Sell</th>
                            </tr>
                            <tr>
                                <td colspan="2" class="checkbox-column">
                                    <label><input type="checkbox" id="sell_alcohol_for_email" '.($data['sell_alcohol']==1?'checked="checked"':'').'/> Do you sell Alcohol?</label>
                                </td>
                            </tr>';
                            if ($data['premises_licence']) {
                                $customer_form_for_docusign .= '<tr>
                                    <td class="label">Premises Licence:</td>
                                    <td class="value">'.$data['premises_licence'].'</td>
                                </tr>';
                            }
                            $customer_form_for_docusign .= '<tr>
                                <td colspan="2" class="checkbox-column">
                                    <label><input type="checkbox" id="sell_tobacco_for_email" '.($data['sell_tobacco']==1?'checked="checked"':'').'/> Do you sell Tobacco?</label>
                                </td>
                            </tr>';
                            if ($data['eoid']) {
                                $customer_form_for_docusign .= '<tr>
                                    <td class="label">EOID:</td>
                                    <td class="value">'.$data['eoid'].'</td>
                                </tr>';
                            }
                            if ($data['fid']) {
                                $customer_form_for_docusign .= '<tr>
                                    <td class="label">FID:</td>
                                    <td class="value">'.$data['fid'].'</td>
                                </tr>';
                            }
                            $customer_form_for_docusign .= '<tr>
                                <td colspan="2" class="checkbox-column">
                                    <label><input type="checkbox" id="sell_vapes_for_email" '.($data['sell_vapes']==1?'checked="checked"':'').'/> Do you sell Vapes?</label>
                                </td>
                            </tr>

                            <tr>
                                <th colspan="2" class="section-title">Store</th>
                            </tr>
                            <tr>
                                <td class="label required">Store size in square feet?</td>
                                <td class="value">'.$data['store_sz'].'</td>
                            </tr>
                            <tr>
                                <td class="label required">Store average turnover weekly?</td>
                                <td class="value">'.$data['store_avg'].'</td>
                            </tr>
                            <tr>
                                <td colspan="2" class="checkbox-column">
                                    <div><label><input type="checkbox" id="self_service_for_email" '.($data['self_service']==1?'checked="checked"':'').'/> I will visit the depot to purchase goods</label></div>
                                    <div><label><input type="checkbox" id="click_and_collect_for_email" '.($data['click_and_collect']==1?'checked="checked"':'').'/> I will order online then come in to collect goods</label></div>
                                    <div><label><input type="checkbox" id="delivered_for_email" '.($data['delivered']==1?'checked="checked"':'').'/> I will order online and require a delivery of goods</label></div>
                                    <div><label><input type="checkbox" id="offers_and_info_for_email" '.($data['offers_and_info']==1?'checked="checked"':'').'/> Do you wish to receive marketing offers and info?</label></div>';
                                    if ($data['offers_and_info']==1 && $data['marketing_options']) {
                                        $available_marketing_options = explode(',', 'post,email,sms,messaging,telephone');
                                        $array_marketing_options = explode(',', $data['marketing_options']);
                                        $customer_form_for_docusign1 = '';
                                        foreach ($available_marketing_options as $available_marketing_options_item) {
                                            if (in_array($available_marketing_options_item, $array_marketing_options)) {
                                                $customer_form_for_docusign1 .= '<label style="padding-left:0px; display: inline-block"><input type="checkbox" id="marketing_option_for_email" checked="checked" /> '.$available_marketing_options_item.'</label>';
                                            } else {
                                                $customer_form_for_docusign1 .= '<label style="padding-left:0px; display: inline-block"><input type="checkbox" id="marketing_option_for_email" /> '.$available_marketing_options_item.'</label>';
                                            }
                                        }
                                        if ($customer_form_for_docusign1) {
                                            $customer_form_for_docusign .= '<div style="display: flex"><span style="padding: 0px 4px 0px 17px">by: </span>'.$customer_form_for_docusign1.'</div>';
                                        }
                                    }
                            $customer_form_for_docusign .= '</td>
                            </tr>

                            <tr>
                                <th colspan="2" class="section-title">Payment &amp; Offer</th>
                            </tr>
                            <tr>
                                <td class="label">What is your preferred payment method?</td>
                                <td class="value">'.$data['pref_payment_method'].'</td>
                            </tr>
                            <tr>
                                <td class="label">Do you require a credit account facility?</td>
                                <td class="">
                                    <label>
                                    <input type="checkbox" id="credit_acc_facility_for_email" '.($data['credit_acc_facility']==1?'checked="checked"':'').'/>
                                    Yes
                                    </label>
                                </td>
                            </tr>';

        if (!empty($data['credit_limit'])) {
            $customer_form_for_docusign .= '
                            <tr>
                                <td class="label required">Required Credit Limit &pound;\'s:</td>
                                <td class="value">'.htmlspecialchars((string) $data['credit_limit']).'</td>
                            </tr>';
        }

        $customer_form_for_docusign .= '
                        </table>
                    </div>';
        $sign_fields_for_docusign = '<table style="width: 100%;">
                        <tr>
                            <td style="width: 50%;">
                                <p>Please sign the document</p>
                            </td>
                            <td style="width: 50%;">
                                <p>Please sign the document</p>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 50%;">
                                <div>Name: <span style="color: white;">/fn1/</span></div>
                                <br>
                                <br>
                            </td>
                            <td style="width: 50%;">
                                <div>Name: <span style="color: white;">/fn2/</span></div>
                                <br>
                                <br>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 50%;">
                                <div>Signed: <span style="color: white;">/sn1/</span></div>
                                <br>
                                <br>
                            </td>
                            <td style="width: 50%;">
                                <div>Signed: <span style="color: white;">/sn2/</span></div>
                                <br>
                                <br>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 50%;">
                                <div>Date: <span style="color: white;">/dt1/</span></div>
                                <br>
                                <br>
                            </td>
                            <td style="width: 50%;">
                                <div>Date: <span style="color: white;">/dt2/</span></div>
                                <br>
                                <br>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" style="width: 100%; color: gray">Please upload photo id of yourself such as a driving licence or passport.</td>
                        </tr>
                        <tr>
                            <td style="width: 50%;">
                                <div>Personal ID: <span style="color: white;">/pat1/</span></div>
                                <br>
                                <br>
                                <br>
                            </td>
                            <td style="width: 50%;"></td>
                        </tr>
                        <tr>
                            <td colspan="2" style="width: 100%; color: gray">Please upload your HMRC VAT registration letter, a bank statement (less than 3 months old), utility bill and a copy on an invoice from a supplier with your business name and address on it.</td>
                        </tr>
                        <tr>
                            <td style="width: 50%;">
                                <div>Business ID: <span style="color: white;">/bat1/</span></div>
                                <br>
                                <br>
                            </td>
                            <td style="width: 50%;"></td>
                        </tr>
                    </table>';

        // Replace the style tag in template_html with style_for_docusign content
        $template_html = str_replace('<style id="style-for-docusign"></style>', $style_for_docusign, $template_html);
        
        // Replace the div element with id="customer-register-form-for-docusign" with customer_form_for_docusign content
        $template_html = preg_replace('/<div id="customer-register-form-for-docusign"[^>]*>.*?<\/div>/s', $customer_form_for_docusign, $template_html);
        
        // Replace the div element with id="sign-fields-for-docusign" with sign_fields_for_docusign content
        $template_html = preg_replace('/<div id="sign-fields-for-docusign"[^>]*>.*?<\/div>/s', $sign_fields_for_docusign, $template_html);

		return $template_html;
	}

    

    // ==================== Private Helper Methods ====================

    /**
     * Get JWT Access Token with caching
     */
    public function getJwtAccessToken($integrationKey, $userId, $oauthBasePath): string
    {
        $cache = \Config\Services::cache();
        $cacheKey = 'docusign_jwt_token';
        
        // Try to get token from cache
        $cachedToken = $cache->get($cacheKey);
        if ($cachedToken) {
            return $cachedToken;
        }

        // Generate new token
        $privateKeyFile = WRITEPATH . 'keys/docusign_private.key';
        
        if (!file_exists($privateKeyFile)) {
            throw new \Exception("Private key file not found at: {$privateKeyFile}");
        }

        $privateKey = file_get_contents($privateKeyFile);
        $jwt = $this->createJwtToken($privateKey, $integrationKey, $userId, $oauthBasePath);
        $tokenData = $this->exchangeJwtForToken($jwt, $integrationKey, $oauthBasePath);

        // Cache token for 50 minutes (tokens expire in 60 minutes)
        $cache->save($cacheKey, $tokenData['access_token'], 3000);

        return $tokenData['access_token'];
    }

    /**
     * Create JWT token
     */
    private function createJwtToken(string $privateKey, $integrationKey, $userId, $oauthBasePath): string
    {
        $header = [
            'typ' => 'JWT',
            'alg' => 'RS256'
        ];

        $payload = [
            'iss' => $integrationKey,
            'sub' => $userId,
            'aud' => str_replace('https://', '', $oauthBasePath),
            'iat' => time(),
            'exp' => time() + 3600,
            'scope' => 'signature impersonation'
        ];

        $headerEncoded = $this->base64urlEncode(json_encode($header));
        $payloadEncoded = $this->base64urlEncode(json_encode($payload));

        $signatureInput = $headerEncoded . '.' . $payloadEncoded;
        openssl_sign($signatureInput, $signature, $privateKey, OPENSSL_ALGO_SHA256);
        $signatureEncoded = $this->base64urlEncode($signature);

        return $signatureInput . '.' . $signatureEncoded;
    }

    /**
     * Exchange JWT for access token
     */
    private function exchangeJwtForToken(string $jwt, $integrationKey, $oauthBasePath): array
    {
        $client = \Config\Services::curlrequest();
        
        try {
            $response = $client->post($oauthBasePath . '/oauth/token', [
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'form_params' => [
                    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                    'assertion' => $jwt
                ],
                'http_errors' => false
            ]);

            $statusCode = $response->getStatusCode();
            $body = $response->getBody();
            $responseData = json_decode($body, true);

            log_message('info', 'DocuSign JWT Exchange - Status: ' . $statusCode);
            log_message('info', 'DocuSign JWT Exchange - Response: ' . $body);

            if ($statusCode !== 200) {
                $errorMsg = 'JWT Token Exchange Failed (Status: ' . $statusCode . ')';
                
                if (isset($responseData['error'])) {
                    $errorMsg .= ' - Error: ' . $responseData['error'];
                    
                    if (isset($responseData['error_description'])) {
                        $errorMsg .= ' - ' . $responseData['error_description'];
                    }
                    
                    // Specific error messages to help debugging
                    if ($responseData['error'] === 'consent_required') {
                        $errorMsg .= "\n\nYou need to grant consent. Visit this URL:\n";
                        $errorMsg .= $oauthBasePath . '/oauth/auth?response_type=code&scope=signature%20impersonation&client_id=' . $integrationKey . '&redirect_uri=https://www.docusign.com';
                    }
                }
                
                throw new \Exception($errorMsg);
            }

            return $responseData;
            
        } catch (\Exception $e) {
            log_message('error', 'DocuSign JWT Exchange Error: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * Create envelope in DocuSign
     */
    public function createEnvelope(string $accessToken, array $envelopeData, string $basePath, string $accountId): array
    {
        $client = \Config\Services::curlrequest();
        
        $response = $client->post(
            "{$basePath}/v2.1/accounts/{$accountId}/envelopes",
            [
                'headers' => [
                    'Authorization' => 'Bearer ' . $accessToken,
                    'Content-Type' => 'application/json'
                ],
                'json' => $envelopeData,
                'http_errors' => false
            ]
        );

        if ($response->getStatusCode() !== 201) {
            $error = json_decode($response->getBody(), true);
            throw new \Exception('Envelope Creation Error: ' . ($error['message'] ?? $response->getBody()));
        }

        return json_decode($response->getBody(), true);
    }

    /**
     * Base64 URL encode
     */
    private function base64urlEncode(string $data): string
    {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

    /**
     * API Endpoint: Get List of Envelopes
     * GET /docusign-api/envelopes
     * 
     * Query Parameters:
     * - from_date: Start date (format: YYYY-MM-DD or ISO 8601)
     * - to_date: End date (format: YYYY-MM-DD or ISO 8601)
     * - status: Envelope status (sent, delivered, completed, declined, voided, etc.)
     * - count: Number of results to return (default: 10, max: 100)
     * - start_position: Starting position for pagination (default: 0)
     * - search_text: Search in email subject or custom fields
     * - folder: Folder to search in (inbox, sentitems, draft, etc.)
     * 
     * Example: GET /docusign-api/envelopes?status=sent&count=20&from_date=2024-01-01
     */
    // public function envelopes()
    // {
    //     try {
    //         $accessToken = $this->getJwtAccessToken();
            
    //         if (!$accessToken) {
    //             return $this->fail('Failed to obtain access token', 500);
    //         }

    //         // Get query parameters
    //         $request = $this->request;
            
    //         // Build query parameters for DocuSign API
    //         $queryParams = [];
            
    //         // Date range (default: last 30 days if not specified)
    //         $fromDate = $request->getGet('from_date');
    //         if ($fromDate) {
    //             // Convert to ISO 8601 format if needed
    //             $queryParams['from_date'] = date('c', strtotime($fromDate));
    //         } else {
    //             // Default: 30 days ago
    //             $queryParams['from_date'] = date('c', strtotime('-30 days'));
    //         }
            
    //         $toDate = $request->getGet('to_date');
    //         if ($toDate) {
    //             $queryParams['to_date'] = date('c', strtotime($toDate));
    //         }
            
    //         // Status filter (sent, delivered, completed, declined, voided)
    //         $status = $request->getGet('status');
    //         if ($status) {
    //             $queryParams['status'] = $status;
    //         }
            
    //         // Pagination
    //         $count = $request->getGet('count') ?: 10;
    //         $count = min((int)$count, 100); // Max 100 per request
    //         $queryParams['count'] = $count;
            
    //         $startPosition = $request->getGet('start_position') ?: 0;
    //         $queryParams['start_position'] = (int)$startPosition;
            
    //         // Search text
    //         $searchText = $request->getGet('search_text');
    //         if ($searchText) {
    //             $queryParams['search_text'] = $searchText;
    //         }
            
    //         // Folder (inbox, sentitems, draft, etc.)
    //         $folder = $request->getGet('folder');
    //         if ($folder) {
    //             $queryParams['folder_types'] = $folder;
    //         }
            
    //         // Order by (default: status_changed descending)
    //         $queryParams['order'] = 'desc';
    //         $queryParams['order_by'] = 'status_changed';
            
    //         // Build query string
    //         $queryString = http_build_query($queryParams);
            
    //         // Call DocuSign API
    //         $client = \Config\Services::curlrequest();
            
    //         $response = $client->get(
    //             "{$this->basePath}/v2.1/accounts/{$this->accountId}/envelopes?{$queryString}",
    //             [
    //                 'headers' => [
    //                     'Authorization' => 'Bearer ' . $accessToken,
    //                     'Content-Type' => 'application/json'
    //                 ],
    //                 'http_errors' => false
    //             ]
    //         );

    //         if ($response->getStatusCode() !== 200) {
    //             $error = json_decode($response->getBody(), true);
    //             throw new \Exception('Failed to fetch envelopes: ' . ($error['message'] ?? $response->getBody()));
    //         }

    //         $result = json_decode($response->getBody(), true);
            
    //         // Format the response
    //         $envelopes = [];
    //         if (isset($result['envelopes']) && is_array($result['envelopes'])) {
    //             foreach ($result['envelopes'] as $envelope) {
    //                 $envelopes[] = [
    //                     'envelope_id' => $envelope['envelopeId'] ?? '',
    //                     'status' => $envelope['status'] ?? '',
    //                     'email_subject' => $envelope['emailSubject'] ?? '',
    //                     'sender_name' => $envelope['sender']['userName'] ?? '',
    //                     'sender_email' => $envelope['sender']['email'] ?? '',
    //                     'created_date_time' => $envelope['createdDateTime'] ?? '',
    //                     'sent_date_time' => $envelope['sentDateTime'] ?? '',
    //                     'status_date_time' => $envelope['statusChangedDateTime'] ?? '',
    //                     'completed_date_time' => $envelope['completedDateTime'] ?? null,
    //                     'documents_count' => $envelope['documentsUri'] ? 1 : 0,
    //                     'recipients_count' => isset($envelope['recipients']) ? count($envelope['recipients']) : 0
    //                 ];
    //             }
    //         }

    //         return $this->respond([
    //             'success' => true,
    //             'total_count' => $result['resultSetSize'] ?? count($envelopes),
    //             'start_position' => $result['startPosition'] ?? 0,
    //             'end_position' => $result['endPosition'] ?? count($envelopes),
    //             'next_uri' => $result['nextUri'] ?? null,
    //             'previous_uri' => $result['previousUri'] ?? null,
    //             'envelopes' => $envelopes,
    //             'filters_applied' => $queryParams
    //         ]);

    //     } catch (\Exception $e) {
    //         log_message('error', 'DocuSign Get Envelopes Error: ' . $e->getMessage());
    //         return $this->fail($e->getMessage(), 500);
    //     }
    // }

    /**
     * API Endpoint: Get Detailed Envelope Information
     * GET /docusign-api/envelope-details/{envelopeId}
     * 
     * Query Parameters:
     * - include_recipients: Include recipient details (default: true)
     * - include_documents: Include document details (default: true)
     * - include_custom_fields: Include custom fields (default: false)
     * 
     * @param string $envelopeId
     */
    public function envelopeDetails($envelopeId = null, $internal_call = false)
    {
        $db = \Config\Database::connect();
        $branch = session()->get('branch');

        // Branch config via the key-value table.
        $branchConfig = (object) \App\Models\BranchConfig::getAll($branch, session()->get('organization_id'));
        $docusign_user_id          = $branchConfig->docusign_user_id          ?? '';
        $docusign_integration_key  = $branchConfig->docusign_integration_key  ?? '';
        $docusign_oauth_base_path  = $branchConfig->docusign_oauth_base_path  ?? '';
        $docusign_account_id       = $branchConfig->docusign_account_id       ?? '';
        $docusign_account_base_uri = $branchConfig->docusign_account_base_uri ?? '';
        $basePath                  = $docusign_account_base_uri . '/restapi';
        
        try {
            if (!$envelopeId) {
                return $this->fail('Envelope ID is required', 400);
            }

            $accessToken = $this->getJwtAccessToken($docusign_integration_key, $docusign_user_id, $docusign_oauth_base_path);
            
            if (!$accessToken) {
                return $this->fail('Failed to obtain access token', 500);
            }

            $request = \Config\Services::request();
            $includeRecipients = $request->getGet('include_recipients') !== 'false';
            $includeDocuments = $request->getGet('include_documents') !== 'false';
            $includeCustomFields = $request->getGet('include_custom_fields') === 'true';

            $client = \Config\Services::curlrequest();
            
            // Get basic envelope info
            $response = $client->get(
                "{$basePath}/v2.1/accounts/{$docusign_account_id}/envelopes/{$envelopeId}",
                [
                    'headers' => [
                        'Authorization' => 'Bearer ' . $accessToken,
                        'Content-Type' => 'application/json'
                    ]
                ]
            );

            $envelope = json_decode($response->getBody(), true);
            
            $details = [
                'envelope_id' => $envelope['envelopeId'],
                'status' => $envelope['status'],
                'email_subject' => $envelope['emailSubject'],
                'email_blurb' => $envelope['emailBlurb'] ?? '',
                'created_date_time' => $envelope['createdDateTime'],
                'sent_date_time' => $envelope['sentDateTime'] ?? null,
                'status_date_time' => $envelope['statusChangedDateTime'],
                'completed_date_time' => $envelope['completedDateTime'] ?? null,
                'voided_date_time' => $envelope['voidedDateTime'] ?? null,
                'voided_reason' => $envelope['voidedReason'] ?? null,
                'sender' => [
                    'name' => $envelope['sender']['userName'] ?? '',
                    'email' => $envelope['sender']['email'] ?? ''
                ]
            ];

            // Get recipients if requested
            if ($includeRecipients) {
                $recipientsResponse = $client->get(
                    "{$basePath}/v2.1/accounts/{$docusign_account_id}/envelopes/{$envelopeId}/recipients",
                    [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $accessToken,
                            'Content-Type' => 'application/json'
                        ]
                    ]
                );
                
                $recipientsData = json_decode($recipientsResponse->getBody(), true);
                $recipients = [];
                
                if (isset($recipientsData['signers'])) {
                    foreach ($recipientsData['signers'] as $signer) {
                        $recipients[] = [
                            'type' => 'signer',
                            'recipient_id' => $signer['recipientId'],
                            'name' => $signer['name'],
                            'email' => $signer['email'],
                            'status' => $signer['status'],
                            'routing_order' => $signer['routingOrder'],
                            'signed_date_time' => $signer['signedDateTime'] ?? null,
                            'delivered_date_time' => $signer['deliveredDateTime'] ?? null,
                            'declined_date_time' => $signer['declinedDateTime'] ?? null,
                            'declined_reason' => $signer['declinedReason'] ?? null
                        ];
                    }
                }
                
                $details['recipients'] = $recipients;
                $details['recipients_count'] = count($recipients);
            }

            // Get documents if requested
            if ($includeDocuments) {
                $documentsResponse = $client->get(
                    "{$basePath}/v2.1/accounts/{$docusign_account_id}/envelopes/{$envelopeId}/documents",
                    [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $accessToken,
                            'Content-Type' => 'application/json'
                        ]
                    ]
                );
                
                $documentsData = json_decode($documentsResponse->getBody(), true);
                $documents = [];
                
                if (isset($documentsData['envelopeDocuments'])) {
                    foreach ($documentsData['envelopeDocuments'] as $doc) {
                        $documents[] = [
                            'document_id' => $doc['documentId'],
                            'name' => $doc['name'],
                            'type' => $doc['type'] ?? 'content',
                            'uri' => $doc['uri'] ?? '',
                            'order' => $doc['order'] ?? 0
                        ];
                    }
                }
                
                $details['documents'] = $documents;
                $details['documents_count'] = count($documents);
            }

            // Get custom fields if requested
            if ($includeCustomFields) {
                $customFieldsResponse = $client->get(
                    "{$basePath}/v2.1/accounts/{$docusign_account_id}/envelopes/{$envelopeId}/custom_fields",
                    [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $accessToken,
                            'Content-Type' => 'application/json'
                        ]
                    ]
                );
                
                $customFieldsData = json_decode($customFieldsResponse->getBody(), true);
                $details['custom_fields'] = $customFieldsData;
            }

            if ($internal_call) {
                return $details;
            } else {
                return $this->respond([
                    'success' => true,
                    'envelope' => $details
                ]);
            }

        } catch (\Exception $e) {
            log_message('error', 'DocuSign Get Envelope Details Error: ' . $e->getMessage());
            if ($internal_call) {
                return false;
            } else {
                return $this->fail($e->getMessage(), 500);
            }
        }
    }

    /**
     * API Endpoint: Download Envelope Document
     * GET /docusign-api/envelope-document/{envelopeId}/{documentId}
     * 
     * @param string $envelopeId
     * @param string $documentId (use 'combined' for all documents in one PDF)
     */
    public function downloadDocument($envelopeId = null, $documentId = 'combined')
    {
        $db = \Config\Database::connect();
        $branch = session()->get('branch');
        // Branch config via the key-value table.
        $branchConfig = (object) \App\Models\BranchConfig::getAll($branch, session()->get('organization_id'));
        $docusign_user_id          = $branchConfig->docusign_user_id          ?? '';
        $docusign_integration_key  = $branchConfig->docusign_integration_key  ?? '';
        $docusign_oauth_base_path  = $branchConfig->docusign_oauth_base_path  ?? '';
        $docusign_account_id       = $branchConfig->docusign_account_id       ?? '';
        $docusign_account_base_uri = $branchConfig->docusign_account_base_uri ?? '';
        $basePath                  = $docusign_account_base_uri . '/restapi';
        
        try {
            if (!$envelopeId) {
                return $this->fail('Envelope ID is required', 400);
            }

            $accessToken = $this->getJwtAccessToken($docusign_integration_key, $docusign_user_id, $docusign_oauth_base_path);
            
            if (!$accessToken) {
                return $this->fail('Failed to obtain access token', 500);
            }

            $client = \Config\Services::curlrequest();
            
            $response = $client->get(
                "{$basePath}/v2.1/accounts/{$docusign_account_id}/envelopes/{$envelopeId}/documents/{$documentId}",
                [
                    'headers' => [
                        'Authorization' => 'Bearer ' . $accessToken
                    ]
                ]
            );

            // Set headers for PDF download
            $filename = "envelope_{$envelopeId}_doc_{$documentId}.pdf";
            
            return $this->response
                ->setHeader('Content-Type', 'application/pdf')
                ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
                ->setBody($response->getBody());

        } catch (\Exception $e) {
            log_message('error', 'DocuSign Download Document Error: ' . $e->getMessage());
            return $this->fail($e->getMessage(), 500);
        }
    }

    /**
     * API Endpoint: Download CSV with customer registration + terms + sign status.
     * GET /docusign-api/envelope-csv/{registrationId}
     *
     * Behavior:
     *  - Always includes the customer's registration form data and terms text.
     *  - If the customer has an envelope_id, include DocuSign status/recipients/documents.
     *  - If no envelope_id, envelope sections are omitted.
     *
     * @param string $registrationId
     */
    public function downloadCsv($registrationId = null)
    {
        $db = \Config\Database::connect();
        $branch = session()->get('branch');
        // Branch config via the key-value table.
        $branchConfig = (object) \App\Models\BranchConfig::getAll($branch, session()->get('organization_id'));
        $docusign_user_id          = $branchConfig->docusign_user_id          ?? '';
        $docusign_integration_key  = $branchConfig->docusign_integration_key  ?? '';
        $docusign_oauth_base_path  = $branchConfig->docusign_oauth_base_path  ?? '';
        $docusign_account_id       = $branchConfig->docusign_account_id       ?? '';
        $docusign_account_base_uri = $branchConfig->docusign_account_base_uri ?? '';
        $basePath                  = $docusign_account_base_uri . '/restapi';

        try {
            if (!$registrationId) {
                return $this->fail('Registration ID is required', 400);
            }

            // --- Fetch registration by ID ---
            $registration = $db->table('epos_customer_registration')
                ->where('id', $registrationId)
                ->get()
                ->getRowArray();

            if (!$registration) {
                return $this->fail('No registration data found for this customer', 404);
            }

            $boolToYesNo = static function ($value) {
                return ((string)$value === '1' || $value === 1 || $value === true) ? 'Yes' : 'No';
            };

            // --- Fetch DocuSign envelope status (optional) ---
            $details = null;
            $envelopeId = $registration['envelope_id'] ?? null;
            if (!empty($envelopeId)) {
              // Non-fatal: the registration form data must always export even if
              // DocuSign is unreachable or the JWT token can't be obtained.
              try {
                $accessToken = $this->getJwtAccessToken($docusign_integration_key, $docusign_user_id, $docusign_oauth_base_path);
                if (!$accessToken) {
                    throw new \RuntimeException('Failed to obtain DocuSign access token');
                }

                $client = \Config\Services::curlrequest();

                // Envelope info
                $response = $client->get(
                    "{$basePath}/v2.1/accounts/{$docusign_account_id}/envelopes/{$envelopeId}",
                    [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $accessToken,
                            'Content-Type' => 'application/json'
                        ]
                    ]
                );
                $envelope = json_decode($response->getBody(), true);

                $details = [
                    'envelope_id' => $envelope['envelopeId'] ?? $envelopeId,
                    'status' => $envelope['status'] ?? '',
                    'email_subject' => $envelope['emailSubject'] ?? '',
                    'email_blurb' => $envelope['emailBlurb'] ?? '',
                    'created_date_time' => $envelope['createdDateTime'] ?? '',
                    'sent_date_time' => $envelope['sentDateTime'] ?? '',
                    'status_date_time' => $envelope['statusChangedDateTime'] ?? '',
                    'completed_date_time' => $envelope['completedDateTime'] ?? '',
                    'voided_date_time' => $envelope['voidedDateTime'] ?? '',
                    'voided_reason' => $envelope['voidedReason'] ?? '',
                    'sender' => [
                        'name' => $envelope['sender']['userName'] ?? '',
                        'email' => $envelope['sender']['email'] ?? ''
                    ]
                ];

                // Recipients / signers
                $recipientsResponse = $client->get(
                    "{$basePath}/v2.1/accounts/{$docusign_account_id}/envelopes/{$envelopeId}/recipients",
                    [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $accessToken,
                            'Content-Type' => 'application/json'
                        ]
                    ]
                );
                $recipientsData = json_decode($recipientsResponse->getBody(), true);
                $recipients = [];
                if (isset($recipientsData['signers'])) {
                    foreach ($recipientsData['signers'] as $signer) {
                        $recipients[] = [
                            'type' => 'signer',
                            'recipient_id' => $signer['recipientId'] ?? '',
                            'name' => $signer['name'] ?? '',
                            'email' => $signer['email'] ?? '',
                            'status' => $signer['status'] ?? '',
                            'routing_order' => $signer['routingOrder'] ?? '',
                            'signed_date_time' => $signer['signedDateTime'] ?? '',
                            'delivered_date_time' => $signer['deliveredDateTime'] ?? '',
                            'declined_date_time' => $signer['declinedDateTime'] ?? '',
                            'declined_reason' => $signer['declinedReason'] ?? ''
                        ];
                    }
                }
                $details['recipients'] = $recipients;

                // Documents metadata (kept for completeness)
                $documentsResponse = $client->get(
                    "{$basePath}/v2.1/accounts/{$docusign_account_id}/envelopes/{$envelopeId}/documents",
                    [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $accessToken,
                            'Content-Type' => 'application/json'
                        ]
                    ]
                );
                $documentsData = json_decode($documentsResponse->getBody(), true);
                $documents = [];
                if (isset($documentsData['envelopeDocuments'])) {
                    foreach ($documentsData['envelopeDocuments'] as $doc) {
                        $documents[] = [
                            'document_id' => $doc['documentId'] ?? '',
                            'name' => $doc['name'] ?? '',
                            'type' => $doc['type'] ?? 'content',
                            'uri' => $doc['uri'] ?? '',
                            'order' => $doc['order'] ?? 0
                        ];
                    }
                }
                $details['documents'] = $documents;
              } catch (\Exception $e) {
                // Skip the envelope section but still export registration data below.
                log_message('error', 'DocuSign Download CSV - envelope section skipped: ' . $e->getMessage());
                $details = null;
              }
            }

            // Terms of services text (same content as contract)
            $termsText = "Wholesale terms and conditions (T&Cs) are critical for business operations to define the financial and legal relationship between a supplier and a retail buyer.\n"
                . "1. Ordering and Minimums: Minimum Order Quantity/Value, ordering process, confirmations.\n"
                . "2. Pricing and Payments: Wholesale pricing, MSRP policy, payment terms (Proforma/Net), accepted methods.\n"
                . "3. Shipping and Delivery: Costs/carriers, risk/title transfer, estimated timelines.\n"
                . "4. Returns and Damages: Reporting window, restocking fees, return authorization.\n"
                . "5. Legal Protections: Limitation of liability, retention of title, governing law.";

            // --- Build CSV content ---
            $csvRows = [];
            $addSection = function ($name) use (&$csvRows) {
                $csvRows[] = ['### ' . $name, ''];
            };
            $addSub = function ($label, $value = '') use (&$csvRows) {
                $csvRows[] = ["\t" . $label, $value];
            };

            // Registration section
            $addSection('Customer Registration Form');
            $addSub('Business Legal Name', $registration['business_legal_name'] ?? '');
            $addSub('Business Trading Name', $registration['business_trading_name'] ?? '');
            $addSub('Business Start Date', $registration['business_start_date'] ?? '');
            $addSub('Address Line 1', $registration['address_line1'] ?? '');
            $addSub('Address Line 2', $registration['address_line2'] ?? '');
            $addSub('County', $registration['county'] ?? '');
            $addSub('City', $registration['city'] ?? '');
            $addSub('Country', $registration['country'] ?? '');
            $addSub('Post Code', $registration['post_code'] ?? '');
            $addSub('Contact Name', $registration['contact_name'] ?? '');
            $addSub('Contact Telephone (Landline)', $registration['contact_telephone_landline'] ?? '');
            $addSub('Contact Telephone (Mobile)', $registration['contact_telephone_mobile'] ?? '');
            $addSub('Contact Email', $registration['contact_email'] ?? '');
            $addSub('Owner House Number', $registration['contact_addr_house_number'] ?? '');
            $addSub('Owner House Name/Flat', $registration['contact_addr_house_name_flat'] ?? '');
            $addSub('Owner Street', $registration['contact_addr_street'] ?? '');
            $addSub('Owner Village/Town', $registration['contact_addr_vill_town'] ?? '');
            $addSub('Owner City', $registration['contact_addr_city'] ?? '');
            $addSub('Owner Country', $registration['contact_addr_country'] ?? '');
            $addSub('Owner Post Code', $registration['contact_addr_postcode'] ?? '');
            $addSub('Company Number', $registration['company_number'] ?? '');
            $addSub('VAT Number', $registration['vat_number'] ?? '');
            $addSub('Business Trading Years', $registration['business_trading_years'] ?? '');
            $addSub('Store Size (sq ft)', $registration['store_size'] ?? '');
            $addSub('Store Average Turnover (weekly)', $registration['store_average'] ?? '');
            $addSub('Preferred Payment Method', $registration['prefered_payment_method'] ?? '');
            $addSub('Credit Account Facility', $boolToYesNo($registration['credit_account_facility'] ?? ''));
            $addSub('Required Credit Limit (£)', $registration['requested_credit_limit'] ?? '');
            $addSub('Offers and Info', $boolToYesNo($registration['offers_and_info'] ?? ''));
            $addSub('Self Service', $boolToYesNo($registration['self_service'] ?? ''));
            $addSub('Click and Collect', $boolToYesNo($registration['click_and_collect'] ?? ''));
            $addSub('Delivered', $boolToYesNo($registration['delivered'] ?? ''));
            $addSub('Confirm Legal Owner/Director', $boolToYesNo($registration['confirm_legal_owner_director'] ?? ''));
            $addSub('Preferred Branch', $registration['prefered_branch'] ?? '');
            $addSub('Sell Alcohol', $boolToYesNo($registration['sell_alcohol'] ?? ''));
            $addSub('Sell Tobacco', $boolToYesNo($registration['sell_tobacco'] ?? ''));
            $addSub('Sell Vapes', $boolToYesNo($registration['sell_vapes'] ?? ''));
            $addSub('Date Created', $registration['date_created'] ?? '');
            $csvRows[] = ['', '']; // spacer

            // Terms of services section
            $addSection('Terms of Services');
            $addSub('Terms Text', $termsText);
            $csvRows[] = ['', '']; // spacer

            // Envelope / sign status section (only if envelope exists)
            if (!empty($details)) {
                $addSection('DocuSign Envelope Status');
                $addSub('Envelope ID', $details['envelope_id'] ?? '');
                $addSub('Status', $details['status'] ?? '');
                $addSub('Email Subject', $details['email_subject'] ?? '');
                $addSub('Email Blurb', $details['email_blurb'] ?? '');
                $addSub('Created Date/Time', $details['created_date_time'] ?? '');
                $addSub('Sent Date/Time', $details['sent_date_time'] ?? '');
                $addSub('Status Changed Date/Time', $details['status_date_time'] ?? '');
                $addSub('Completed Date/Time', $details['completed_date_time'] ?? '');
                $addSub('Voided Date/Time', $details['voided_date_time'] ?? '');
                $addSub('Voided Reason', $details['voided_reason'] ?? '');
                $addSub('Sender Name', $details['sender']['name'] ?? '');
                $addSub('Sender Email', $details['sender']['email'] ?? '');
                $csvRows[] = ['', ''];

                if (!empty($details['recipients'])) {
                    $addSection('Recipients');
                    $csvRows[] = [
                        "\tType",
                        'Recipient ID',
                        'Name',
                        'Email',
                        'Status',
                        'Routing Order',
                        'Signed Date/Time',
                        'Delivered Date/Time',
                        'Declined Date/Time',
                        'Declined Reason'
                    ];
                    foreach ($details['recipients'] as $recipient) {
                        $csvRows[] = [
                            "\t" . ($recipient['type'] ?? ''),
                            $recipient['recipient_id'] ?? '',
                            $recipient['name'] ?? '',
                            $recipient['email'] ?? '',
                            $recipient['status'] ?? '',
                            $recipient['routing_order'] ?? '',
                            $recipient['signed_date_time'] ?? '',
                            $recipient['delivered_date_time'] ?? '',
                            $recipient['declined_date_time'] ?? '',
                            $recipient['declined_reason'] ?? ''
                        ];
                    }
                    $csvRows[] = ['', ''];
                }

                if (!empty($details['documents'])) {
                    $addSection('Documents');
                    $csvRows[] = [
                        "\tDocument ID",
                        'Name',
                        'Type',
                        'Order',
                        'URI'
                    ];
                    foreach ($details['documents'] as $document) {
                        $csvRows[] = [
                            "\t" . ($document['document_id'] ?? ''),
                            $document['name'] ?? '',
                            $document['type'] ?? '',
                            $document['order'] ?? '',
                            $document['uri'] ?? ''
                        ];
                    }
                }
            }

            // Convert to CSV string
            $csvContent = '';
            foreach ($csvRows as $row) {
                $escapedRow = array_map(function($field) {
                    $field = str_replace('"', '""', (string)$field);
                    if (strpos($field, ',') !== false || strpos($field, "\n") !== false || strpos($field, '"') !== false) {
                        return '"' . $field . '"';
                    }
                    return $field;
                }, $row);
                $csvContent .= implode(',', $escapedRow) . "\n";
            }

            // Set headers for CSV download
            $filename = "customer_registration_{$registrationId}.csv";

            return $this->response
                ->setHeader('Content-Type', 'text/csv; charset=UTF-8')
                ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
                ->setHeader('Content-Transfer-Encoding', 'binary')
                ->setBody($csvContent);

        } catch (\Exception $e) {
            log_message('error', 'DocuSign Download CSV Error: ' . $e->getMessage());
            return $this->fail($e->getMessage(), 500);
        }
    }

    /**
     * API Endpoint: Get Customer Info and Config
     * GET /docusign-api/customer-info-config/{customerId}
     * 
     * Returns customer registration information and account creation API config
     * 
     * @param string $customerId
     */
    public function getCustomerInfoAndConfig($customerId = null)
    {
        try {
            if (!$customerId) {
                return $this->fail('Customer ID is required', 400);
            }
            
            $db = \Config\Database::connect();
            
            // Get registration data using customer_id (which is the registration ID)
            $registration = $db->table('epos_customer_registration')
                ->where('id', $customerId)
                ->get()
                ->getRowArray();
            
            if (!$registration) {
                return $this->fail('Registration not found', 404);
            }
            
            // Get external API URL and key from config
            $apiUrlResult = $db->table('epos_app_config')->where('key', 'account_create_api_url')->get()->getRow();
            $apiKeyResult = $db->table('epos_app_config')->where('key', 'account_create_api_key')->get()->getRow();
            
            $accountCreateApiUrl = $apiUrlResult && !empty($apiUrlResult->value) ? $apiUrlResult->value : null;
            $accountCreateApiKey = $apiKeyResult && !empty($apiKeyResult->value) ? $apiKeyResult->value : null;
            
            return $this->respond([
                'success' => true,
                'customer_info' => $registration,
                'account_create_api_url' => $accountCreateApiUrl,
                'account_create_api_key' => $accountCreateApiKey
            ]);
            
        } catch (\Exception $e) {
            log_message('error', 'Get Customer Info and Config Error: ' . $e->getMessage());
            return $this->fail($e->getMessage(), 500);
        }
    }

    /**
     * API Endpoint: Update MMS Creator ID
     * POST /docusign-api/update-mms-creator/{customerId}
     * 
     * Updates the mms_creator_id and mms_creator_sop fields in epos_customer_registration table
     * with the current logged-in employee ID and SOP value
     * 
     * Request Body:
     * {
     *   "sop": true or false
     * }
     * 
     * @param string $customerId
     */
    public function updateMmsCreator($customerId = null)
    {
        try {
            if (!$customerId) {
                return $this->fail('Customer ID is required', 400);
            }
            
            // Get logged-in employee ID from session
            $employeeId = session()->get('person_id');
            
            if (!$employeeId) {
                return $this->fail('User not logged in', 401);
            }
            
            // Get SOP value from request body
            $request = $this->request;
            $data = $request->getJSON(true);
            $sop = isset($data['sop']) ? (bool)$data['sop'] : null;
            
            $db = \Config\Database::connect();
            
            // Prepare update data
            $updateData = ['mms_creator_id' => $employeeId];
            
            // Add SOP value if provided
            if ($sop !== null) {
                $updateData['mms_creator_sop'] = $sop ? 1 : 0;
            }
            
            // Update mms_creator_id and mms_creator_sop in epos_customer_registration table
            $updated = $db->table('epos_customer_registration')
                ->where('id', $customerId)
                ->update($updateData);
            
            if ($updated === false) {
                return $this->fail('Failed to update MMS creator information', 500);
            }
            
            return $this->respond([
                'success' => true,
                'msg' => 'MMS creator information updated successfully',
                'customer_id' => $customerId,
                'mms_creator_id' => $employeeId,
                'mms_creator_sop' => $sop !== null ? ($sop ? 1 : 0) : null
            ]);
            
        } catch (\Exception $e) {
            log_message('error', 'Update MMS Creator ID Error: ' . $e->getMessage());
            return $this->fail($e->getMessage(), 500);
        }
    }
}