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

use Brick\Money\Context\AutoContext;
use Brick\Money\CurrencyConverter;
use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider;
use Brick\Money\ExchangeRateProvider\PDOProvider;
use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration;
use Brick\Money\Money;

class Invoices  extends CI_Controller
{
	private $context = null;

	function __construct()
	{
		parent::__construct();

		// Load member model
		$this->load->model('pagination/Invoices_model', 'model');

		// set to whatever your rates are relative to
		$baseCurrency = 'USD';

		// use your own credentials, or re-use your existing PDO connection
		$pdo = new PDO('mysql:host=' . $this->db->hostname . ';dbname=' . $this->db->database, $this->db->username, $this->db->password);

		$configuration = new PDOProviderConfiguration();

		$configuration->tableName = 'exchange_rate';
		$configuration->exchangeRateColumnName = 'exchange_rate';
		$configuration->targetCurrencyColumnName = 'target_currency';
		$configuration->sourceCurrencyCode = $baseCurrency;

		// this provider loads exchange rates from your database
		$provider = new PDOProvider($pdo, $configuration);

		// this provider calculates exchange rates relative to the base currency
		$provider = new BaseCurrencyProvider($provider, $baseCurrency);

		// this currency converter can now handle any currency pair
		$this->context = new AutoContext();
	}


	function getLists()
	{
		$data = $row = array();

		// Fetch member's records
		$witData = $this->model->getRows($_POST);

		$i = $_POST['start'];
		$current_url = $_POST['currentURL'];
		foreach ($witData as $row) {
			$amount =  Money::of(round($row->amount, 2), $row->currency_code, $this->context)->formatTo('fr_FR');
			$insured_amount =  Money::of(round($row->insured_amount, 2), $row->currency_code, $this->context)->formatTo('fr_FR');
			$insurer_amount =  Money::of(round($row->insurer_amount, 2), $row->currency_code, $this->context)->formatTo('fr_FR');

			$data[] = array($row->invoice_id , $row->institution_name , $amount , $insured_amount, $insurer_amount,
				$row->period_start_at, $row->period_end_at, mb_strtoupper($this->lang->line($row->state),'UTF-8'), '<a href="'.$row->file_url.'" class="btn btn-primary" target="_blank"> '.$this->lang->line('Voir plus...').'</a>');
		}

		$output = array(
			"draw" => $_POST['draw'],
			"recordsTotal" => $this->model->countAll($_POST),
			"recordsFiltered" => $this->model->countFiltered($_POST),
			"data" => $data,
		);

		// Output to JSON format
		echo json_encode($output);
	}

}
