<?php

class MigrationController extends Controller
{

    public function accessRules()
    {
        return array(
            array(
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login', 'error', 'logout'),
                'users' => array('*'),
            ),
            array(
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('Index', 'GenerateAccessToken','UpdateInvoiceData','GetInvoiceData','UploadInvoicedata','UploadCustomerData','UploadCustomerContactData',
                'UploadVendorData','UploadSalesorderData','UploadPurchaseorderData','UploadStoreData'),
            ),
            array(
                'deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function nactioIndex()
    {
        $this->render('index');
    }
    
    public function actionGenerateAccessToken(){
        
        
        $code = "1000.bde78ade58c4a218973402cdb840726e.f5aeda5cf492e15abe56334fd7920bf4"; // Get the authorization code from the URL
        $client_id = '1000.IDNRKPMF667CFS42BNJYM93SES5HZM';
        $redirect_uri = 'http://www.zoho.com/books';
        $client_secret = '38204695e30c60ca1bfd36f02cca520de51fdcc18d';
        
        $url = 'https://accounts.zoho.com/oauth/v2/token';
        
        $data = [
            'grant_type' => 'authorization_code',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'redirect_uri' => $redirect_uri,
            'code' => $code,
            //'scope' => 'ZohoBooks.fullaccess.all'
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $token_info = json_decode($response, true);
        
        echo '<pre>';
        print_r($token_info);
        
        if (isset($token_info['access_token'])) {
            $access_token = $token_info['access_token'];
            
            echo $access_token;
            // You can now use this access token for API requests
        } else {
            // Handle error
            echo "Error retrieving access token: " . $response;
        }

        
        
       /* 
        $code = 
        
        $scope = 'ZohoBooks.fullaccess.all'; // e.g., 'ZohoBooks.fullaccess.all'
        $auth_url = "https://accounts.zoho.com/oauth/v2/auth?response_type=code&client_id={$client_id}&scope={$scope}&redirect_uri={$redirect_uri}";
        https://accounts.zoho.com/oauth/v2/token?code=1000.1408669cd6ed8a9ce3a41253266cddc1.38a8e59e70140cbbc0d2ea5ce6a59498&client_id=1000.IDNRKPMF667CFS42BNJYM93SES5HZM&client_secret=38204695e30c60ca1bfd36f02cca520de51fdcc18d&redirect_uri=http://www.zoho.com/books&grant_type=authorization_code
        // Redirect user to this URL
        header("Location: $auth_url");*/
        exit;

    }
    
    public function actionGetInvoiceData(){
        
     

function fetchAllInvoices($accessToken) {
    $baseUrl = 'https://www.zohoapis.com/books/v3/invoices/?organization_id=799526421&start_date=2024-01-01&end_date=2024-01-31';
    $page = 1;
    $allInvoices = [];

    do {
        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $baseUrl . '?page=' . $page . '&per_page=1000');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Zoho-oauthtoken ' . $accessToken,
            'Content-Type: application/json',
        ]);

        // Execute the request
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // Check for errors
        if (curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
            break;
        }

        // Decode the JSON response
        $data = json_decode($response, true);

        // Check if the request was successful
        if ($httpCode === 200) {
            // Add invoices to the list
            if (isset($data['invoices'])) {
                $allInvoices = array_merge($allInvoices, $data);
                
                //$allInvoices[] = $data['invoices'];
            }
            // Check if there are more pages
            $hasMorePages = isset($data['has_more_page']) && $data['has_more_page'];
        } else {
            echo 'Error fetching invoices: ' . $data['message'];
            break;
        }

        // Close cURL session
        curl_close($ch);

        // Increment page number
        $page++;
    } while ($hasMorePages);

    return $allInvoices;
}

// Usage
$accessToken = '1000.291c42e0be207b75372f9b669ebdc95a.6f3c7d293f1f97af058084344e268f2f'; // Replace with your actual access token
$invoices = fetchAllInvoices($accessToken);

// Print all invoices
echo json_encode($invoices, JSON_PRETTY_PRINT);


        
        
        /*$access_token = '1000.d5bfda4db79a213001fe69d46a0f88aa.27f395a942d0aa9bf0653e370f5997a1'; // Use the access token obtained earlier
        $organization_id = '799526421'; // Your Zoho Books organization ID
        $invoice_id = 'INVOICE_ID'; // The ID of the invoice you want to retrieve
        
        //$url = "https://books.zoho.com/api/v3/invoices/$invoice_id";
        
        $url = "https://www.zohoapis.com/books/v3/invoices";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Zoho-oauthtoken $access_token",
            "X-com-zoho-books-organizationid: $organization_id"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $invoice_data = json_decode($response, true);
        
        if (isset($invoice_data['invoices'])) {
            // Successfully retrieved invoice data
            //echo '<pre>';
            //print_r($invoice_data['invoice']);
            
            
            foreach ($invoice_data['invoices'] as $invoice) {

                // Check if customer_name exists
                //$checkCustomerStmt->execute([':customer_name' => $invoice['customer_name']]);
                //$customer = $checkCustomerStmt->fetch(PDO::FETCH_ASSOC);
                /*if ($customer) {
                  //  echo $invoice['customer_name'];
                   $customerId = $customer['id'];
                }else{
                    
                }
                
                //echo $invoice['invoice_id']."<br>";
                
        $invoice_id = $invoice['invoice_id']; // The ID of the invoice you want to retrieve
        
        //$url = "https://books.zoho.com/api/v3/invoices/$invoice_id";
        
        $url = "https://www.zohoapis.com/books/v3/invoices/".$invoice_id;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Zoho-oauthtoken $access_token",
            "X-com-zoho-books-organizationid: $organization_id"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response_item = curl_exec($ch);
        
         $invoice_items = json_decode($response_item , true);
         
         echo '<pre>';
         print_r($invoice_items);exit;
        
        print_r($response_item);
        curl_close($ch);

               /* $stmt->execute([
                    ':invoice_no'         => $invoice['invoice_number'],
                    ':customer_id'        => $customerId,
                    ':invoice_date'       => $invoice['date'],
                    ':reference'          => $invoice['reference_number'],
                    ':sales_group_id'     => 1,
                    ':currency_id'     => 1,
                    ':exchange_rate'     => 1.00,
                    ':invoice_type'     => 1,
                    ':net_amount'     => $invoice['total'],
                    ':billing_address'    => $invoice['billing_address']['address'],
                    ':shipping_by'    => $invoice['shipping_address']['address'],
                    ':created_by' => Yii::app()->user->id,
                    ':created_datetime' => date('Y-m-d h:i:s'),
            }
            
        } else {
            // Handle error
            echo "Error retrieving invoice: " . $response;
        }*/

    }


    public function actionUpdateInvoiceData()
    {
        
        $jsonFile = 'upload/invoicefromzoho.txt'; 
        $jsonData = file_get_contents($jsonFile);
        $data = json_decode($jsonData, true);
        echo $data['invoice_id'];
        //exit;
        //echo '<pre>';
        //print_r($data['invoices']);

        // Check if the JSON was properly decoded
        if (json_last_error() !== JSON_ERROR_NONE) {
            die('Error decoding JSON: ' . json_last_error_msg());
        }

            try {
                
                
                foreach ($data['invoices'] as $invoice) {
                    
                    //echo $invoice['invoice_id']."customer_id=".$invoice['customer_id'];
                    //echo '<pre>';
                //print_r($invoice);
                    
                    $modelInvoice = new Invoice();
                    
                    $billing_address = "";
                    
                    if(!empty($invoice['billing_address']['address'])){
                        $billing_address.=$invoice['billing_address']['address']."<br>";
                    }
                    if(!empty($invoice['billing_address']['street2'])){
                        $billing_address.=", ".$invoice['billing_address']['street2'];
                    }
                    if(!empty($invoice['billing_address']['city'])){
                        $billing_address.=", ".$invoice['billing_address']['city'];
                    }
                    if(!empty($invoice['billing_address']['state'])){
                        $billing_address.=", ".$invoice['billing_address']['state'];
                    }
                    if(!empty($invoice['billing_address']['zipcode'])){
                        $billing_address.=", ".$invoice['billing_address']['zipcode'];
                    }
                    if(!empty($invoice['billing_address']['country'])){
                        $billing_address.=", ".$invoice['billing_address']['country'];
                    }
                    
                    $shipping_address = "";
                    
                    if(!empty($invoice['shipping_address']['address'])){
                        $shipping_address.=$invoice['shipping_address']['address']."<br>";
                    }
                    if(!empty($invoice['shipping_address']['street2'])){
                        $shipping_address.=", ".$invoice['shipping_address']['street2'];
                    }
                    if(!empty($invoice['shipping_address']['city'])){
                        $shipping_address.=", ".$invoice['shipping_address']['city'];
                    }
                    if(!empty($invoice['shipping_address']['state'])){
                        $shipping_address.=", ".$invoice['shipping_address']['state'];
                    }
                    if(!empty($invoice['shipping_address']['zipcode'])){
                        $shipping_address.=", ".$invoice['shipping_address']['zipcode'];
                    }
                    if(!empty($invoice['shipping_address']['country'])){
                        $shipping_address.=", ".$invoice['shipping_address']['country'];
                    }
                    
                    $modelInvoice->id = $invoice['invoice_id'];
                    $modelInvoice->customer_id = $invoice['customer_id'];
                    $modelInvoice->customer_name = $invoice['customer_name'];
                    $modelInvoice->invoice_status = $invoice['status'];
                    $modelInvoice->invoice_number = $invoice['invoice_number'];
                    $modelInvoice->reference_number = $invoice['reference_number'];
                    $modelInvoice->invoice_date = $invoice['date'];
                    $modelInvoice->invoice_due_date = $invoice['due_date'];
                    $modelInvoice->billing_address = $billing_address;
                    $modelInvoice->shipping_address = $shipping_address;
                    $modelInvoice->total_amount = $invoice['total'];
                    $modelInvoice->balance_amount = $invoice['balance'];
                    $modelInvoice->grand_total = $invoice['sub_total'];
                    $modelInvoice->salesperson_name = $invoice['salesperson_name'];
                    $modelInvoice->salesperson_id = $invoice['salesperson_id'];
                    $modelInvoice->created_time = $invoice['created_time'];
                    $modelInvoice->updated_time = $invoice['updated_time'];
                    $modelInvoice->currency_code = $invoice['currency_code'];
                    $modelInvoice->currency_symbol = $invoice['currency_symbol'];
                    $modelInvoice->exchange_rate = $invoice['exchange_rate'];
                    $modelInvoice->created_by = $invoice['created_by'];
                    $modelInvoice->save(false);
                    //exit;
                
                }  
                
                echo $invoice['invoice_id'];
                echo "Success";
            } catch (PDOException $e) {
                echo "Error: " . $e->getMessage();
            }
    }
}
?>
