public function downloadSettlementFiles()
{
$this->load->language('extension/payment/klarna_checkout');
$this->load->model('extension/payment/klarna_checkout');
$this->load->model('sale/order');
$json = array();
$error = array();
$klarna_checkout_directory = DIR_UPLOAD . 'klarna_checkout/';
if (isset($this->request->post['username'])) {
$username = $this->request->post['username'];
} else {
$username = '';
}
if (isset($this->request->post['password'])) {
$password = html_entity_decode($this->request->post['password']);
} else {
$password = '';
}
if (isset($this->request->post['order_status_id'])) {
$order_status_id = $this->request->post['order_status_id'];
} else {
$order_status_id = false;
}
if (!$username || !$password || !$order_status_id) {
$error[] = 'Please supply a username, password and order status';
}
if (!$error) {
// Connect to the site via FTP
$connection = ftp_connect('mft.klarna.com', '4001');
$files = array();
if ($connection) {
$login = ftp_login($connection, $username, $password);
if ($login) {
$files = ftp_nlist($connection, '.');
rsort($files);
if (!is_dir($klarna_checkout_directory)) {
mkdir($klarna_checkout_directory, 0777);
}
// Save all files to local
foreach (array_diff($files, array('.', '..')) as $file) {
if (!ftp_get($connection, $klarna_checkout_directory . $file, $file, FTP_BINARY)) {
$error[] = 'There was a problem saving one or more files';
}
}
}
}
}
$orders_to_process = array();
$files = scandir($klarna_checkout_directory);
if (!$error) {
// Loop local files and process
foreach (array_diff($files, array('.', '..')) as $file) {
$handle = fopen($klarna_checkout_directory . $file, 'r');
// Skip first 2 lines, use third as headings
fgetcsv($handle);
fgetcsv($handle);
$headings = fgetcsv($handle);
while ($data = fgetcsv($handle)) {
$row = array_combine($headings, $data);
if ($row['type'] == 'SALE') {
$order_id = $this->encryption->decrypt($row['merchant_reference1']);
$klarna_order_info = $this->model_extension_payment_klarna_checkout->getOrder($order_id);
$order_info = $this->model_sale_order->getOrder($order_id);
// Check if order exists in system, if it does, pass back to process
if ($klarna_order_info && $order_info && $order_info['payment_code'] == 'klarna_checkout' && $order_info['order_status_id'] != $order_status_id) {
$orders_to_process[] = $order_id;
}
}
}
fclose($handle);
}
}
// Delete local files
foreach (array_diff($files, array('.', '..')) as $file) {
if (!unlink($klarna_checkout_directory . $file)) {
$error[] = 'Cannot delete files';
}
}
if ($error) {
$orders_to_process = array();
}
$json['error'] = $error;
$json['orders'] = $orders_to_process;
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}