<?php
	
  class Efactura extends AdminController {
	
    public function __construct()
    {
        parent::__construct();
    }
	
		/* eFactura config info */
    public function index()	{

      // Load the helper
      $this->load->helper('efactura_api');

      // Call the helper
      $apiHelper = new Efactura_api();

      // Need to have financial permission to access this module
      if (!has_permission('financial', '', 'bank')) {
          access_denied('financial');
      }

      // Raw body data for the API request
      // The company id would be the instance uniqueid ( we will generate later in a migration)
      $bodyData = [
        'company_id' => get_option('instance_id'),
        'fiscal_code' => get_option('company_vat')
      ];

      $response = $apiHelper->makeApiCall('get-company-anaf-token', 'POST', [], $bodyData);

      if (isset($response['error']) && $response['error'] === true) {
          // Means we will not have yet a token so we will get the url to generate one
          $data['message'] = $response['message'];
      } else {
          // That means we have a token and that's good to go
          $data['token'] = $response['token'];
      }

      // Set the page title
      $data['title'] = _l('efactura_config_title');

      // Load the view
      $this->load->view('config/efactura', $data);
	}

    public function build() {

        $this->load->helper('efactura_invoice');
        $this->load->model('invoices_model');

        $builder = new EfacturaInvoiceBuilder();
        $jsonInvoice = $builder->buildInvoiceFromId(725);
    }

	public function factura() {

      $this->load->helper('efactura_invoice');
      $this->load->model('invoices_model');
      $invoice = $this->invoices_model->get(698);
      
      // Encode the variable for prettified display
      $prettifiedInvoice = json_encode($invoice, JSON_PRETTY_PRINT);


      $builder = new EfacturaInvoiceBuilder();
      $jsonInvoice = $builder->buildInvoiceFromId(725);

      
      // Display the prettified variable in the browser
      echo "<pre>";
      echo $jsonInvoice;
      echo "</pre>";
      die;

      // Load the helper
      $this->load->helper('efactura_api');

      // Call the helper
      $apiHelper = new Efactura_api();

      // Need to have financial permission to access this module
      if (!has_permission('financial', '', 'bank')) {
          access_denied('financial');
      }

      // Raw body data for the API request
      // The company id would be the instance uniqueid ( we will generate later in a migration)
      $bodyData = [
        'company_id' => get_option('instance_id'),
        'fiscal_code' => get_option('company_vat')
      ];
      
      $response = $apiHelper->makeApiCall('get-company-anaf-token', 'POST', [], $bodyData);

      if (isset($response['error']) && $response['error'] === true) {
          // Means we will not have yet a token so we will get the url to generate one
          $data['message'] = $response['message'];
      } else {
          // That means we have a token and that's good to go
          $data['token'] = $response['token'];
      }

      // Set the page title
      $data['title'] = _l('efactura_config_title');

      // Load the view
      $this->load->view('config/efactura', $data);
	}

    /**
     * Generate an XML invoice from an invoice id
     * params: $id - the invoice id
     */
    public function generate_xml($id)
    {
        // Load necessary helpers and libraries
        $this->load->helper('efactura_api');
        $this->load->helper('efactura_invoice');
    
        // Create an instance of the EfacturaInvoiceBuilder
        $builder = new EfacturaInvoiceBuilder();
    
        // Build the JSON invoice data
        $jsonInvoice = $builder->buildInvoiceFromId($id);
    
        // Create an instance of the Efactura_api
        $efacturaApi = new Efactura_api();
    
        // Endpoint for sending the invoice
        $endpoint = 'send-invoice';
        //var_dump($jsonInvoice);die;
    
        // Make the API call to send the invoice
        $response = $efacturaApi->makeApiCallRaw($endpoint, 'POST', [], $jsonInvoice);
        

        
        // Handle the response
        if (isset($response['error']) && $response['error'] == true) {
            // Handle the error
            echo 'Error: ' . $response['message'];
        } else {
            // Construct the XML response
            $xmlContent = $response['xml'];

            // Set the XML content type
            $this->output->set_content_type('text/xml');

            // Generate a unique filename for the downloaded file (optional)
            $filename = 'invoice_' . date('Y-m-d_H-i-s') . '.xml';

            // Force download the XML content with the specified filename
            $this->load->helper('download');
            force_download($filename, $xmlContent);
        }
    }

    /**
     * Send an invoice to the eFactura API
     * params: $id - the invoice id and $target - where to redirect after the API call
     */
    public function send_invoice($id, $target = 'list')
    {
        // Load necessary helpers and libraries
        $this->load->helper('efactura_api');
        $this->load->helper('efactura_invoice');
    
        // Create an instance of the EfacturaInvoiceBuilder
        $builder = new EfacturaInvoiceBuilder();
    
        // Build the JSON invoice data
        $jsonInvoice = $builder->buildInvoiceFromId($id, 1);
    
        // Create an instance of the Efactura_api
        $efacturaApi = new Efactura_api();
    
        // Endpoint for sending the invoice
        $endpoint = 'send-invoice';
  
    
        // Make the API call to send the invoice
        $response = $efacturaApi->makeApiCallRaw($endpoint, 'POST', [], $jsonInvoice);

        $this->load->model('invoices_model');
  
        // Handle the response
        if (isset($response['error']) && $response['error'] == true) {
            // Handle the error
            echo 'Error: ' . $response['message'];
        } else {
            $data = [
                'eindex' => $response['message'],
                'estatus' => 'trimis',
                'esent' => true
            ];
            // Load invoice model
            $this->invoices_model->updateColumns($id, $data);
        }

        // Perform action based on $target parameter
        switch ($target) {
            case 'list':
                redirect(admin_url('invoices/list_invoices/' . $id));
                break;
            // Add more cases as needed
            default:
                redirect(admin_url('invoices/list_invoices/' . $id)); // Default redirect
                break;
        }
    }

    /**
     * Get the status of an invoice from the eFactura API
     * params: $id - the invoice id and $target - where to redirect after the API call
     * no redirect needed for now
     */
    public function invoice_status($id, $target = 'list')
    {
        // Load necessary helpers and libraries
        $this->load->helper('efactura_api');
        $this->load->helper('efactura_invoice');
    
        // Create an instance of the EfacturaInvoiceBuilder
        $builder = new EfacturaInvoiceBuilder();
    
        // Build the JSON invoice data
        $jsonInvoice = $builder->buildInvoiceStatusData($id);

        if(!$jsonInvoice) {
            return;
        }
    
        // Create an instance of the Efactura_api
        $efacturaApi = new Efactura_api();
    
        // Endpoint for sending the invoice
        $endpoint = 'invoice-status';
    
        // Make the API call to send the invoice
        $response = $efacturaApi->makeApiCall($endpoint, 'POST', [], $jsonInvoice);

        $this->load->model('invoices_model');
  
        // Handle the response
        if (isset($response['error']) && $response['error'] == true) {
            // Handle the error
            echo 'Error: ' . $response['message'];
        } else {
            $data = [
                'estatus' => $response['message'],
                'esent' => true
            ];
            // Load invoice model
            $this->invoices_model->updateColumns($id, $data);
        }

        // Perform action based on $target parameter
        switch ($target) {
            case 'list':
                redirect(admin_url('invoices/list_invoices/' . $id));
                break;
            // Add more cases as needed
            default:
                redirect(admin_url('invoices/list_invoices/' . $id)); // Default redirect
                break;
        }
    }

    /**
     * Download an invoice archive from the eFactura API
     * params: $id - the invoice id and $target - where to redirect after the API call
     */
    public function download_archive($id, $target = 'list')
    {
        // Load necessary helpers and libraries
        $this->load->helper('efactura_api');
        $this->load->helper('efactura_invoice');
        $this->load->helper('download'); // Load the Download Helper
    
        // Create an instance of the EfacturaInvoiceBuilder
        $builder = new EfacturaInvoiceBuilder();
    
        // Build the JSON invoice data
        $jsonInvoice = $builder->buildDownloadArchiveData($id);
    
        // Create an instance of the Efactura_api
        $efacturaApi = new Efactura_api();
    
        // Endpoint for sending the invoice
        $endpoint = 'download-invoice';
  
        
        // Make the API call to send the invoice
        $response = $efacturaApi->makeGetApiCall($endpoint, $jsonInvoice);

        // Check if the API call was successful and if the response is valid
        if ($response !== false) {

            // Prepare the headers to force download
            $file_name = 'invoice-' . $id .'.zip';

            force_download($file_name, $response);


            
            // Perform action based on $target parameter
            switch ($target) {
                case 'list':
                    redirect(admin_url('invoices/list_invoices/' . $id));
                    break;
                // Add more cases as needed
                default:
                    redirect(admin_url('invoices/list_invoices/' . $id)); // Default redirect
                    break;
            }
        } else {
            // Maybe we crate an error template here
            switch ($target) {
                case 'list':
                    redirect(admin_url('invoices/list_invoices/' . $id));
                    break;
                // Add more cases as needed
                default:
                    redirect(admin_url('invoices/list_invoices/' . $id)); // Default redirect
                    break;
            }
        }

    }
  
}
	
	
