<?php
include 'webroot/iso/my/html/f.php';

class SalesController extends AppController
{

	var $name = 'Sales';

	var $components = array(
		'Filter' => array(
			'index' => array(
				'customer_id' => array(
					'form_options' => array('label' => 'Customer', 'options' => 'Customers'),
					'filter_options' => array(),
				),
				'payment_type_id' => array(
					'form_options' => array('label' => 'Način plaćanja'),
				),
				//'canceled_by' => array(
				//	        'form_options' => array('label' => 'Status', 'options' => 'Filter.Receiving_cancel'),
				//      	'filter_options' => array(),
				//),
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
				//				'date' => array(
//        	        'form_options' => array('label' => 'Date', 'type' => 'date'),
//	            	'filter_options' => array('fields' => array('DATE(date)')),
//				)
			)
		),
	);

	function beforeFilter()
	{
		parent::beforeFilter();
		// Dopušta pristup akciji email (ako ne zahtijevate autentikaciju za tu akciju)
		$this->Auth->allow('email');
		$this->Auth->allow('testEmail');
		$this->Auth->allow('testPdf');
		$this->Auth->allow('savePdf');
		$this->Auth->allow('sendPdfEmail');
		$this->Auth->mapActions(array('cancel' => 'delete', 'cancelItem' => 'delete', 'send_email' => 'read'));

		$l_id = $this->Session->read('Auth.User.id');

		// Omogućujemo iznimku za određene akcije (npr. print_sale)
		$allowedActions = ['print_sale']; // Dodajte ovdje metode koje trebaju raditi bez autentifikacije

		if (in_array($this->action, $allowedActions)) {
			return; // Preskočimo autentifikaciju za ove metode
		}

		if (empty($l_id)) {
			$this->redirect(array('controller' => 'users', 'action' => 'login')); // Preusmjeravanje na login
			return;
		}
	}

	function index()
	{
		$this->Sale->recursive = 0;
		$this->set('items', $this->paginate());
	}

	function view($id = null)
	{
		$this->Sale->contain('Customer', 'PaymentType', 'SaleItem.Product.ProductGroup', 'RetailItem.Article');
		if (!$id || !($item = $this->Sale->read(null, $id))) {
			$this->Session->setFlash(__('Invalid Sale', true) . ($id ? " #{$id}" : ""), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('item', $item);
	}

	function add()
	{
		if (!empty($this->data)) {

			// process Sale and calculate product prices (with discounts) and total price
			$prices = $this->Sale->SaleItem->Product->find('list', array('fields' => array('Product.price')));
			$total_price = 0;
			foreach ($this->data['SaleItem'] as &$i) {
				$price = $base_price = $i['amount'] * $prices[$i['product_id']];
				if (!empty($i['discount_percent']) && is_numeric($i['discount_percent'])) {
					$price *= (1 - $i['discount_percent'] / 100);
				} else {
					$price = $base_price;
					$i['discount_percent'] = 0;
				}

				$i['base_price'] = $base_price / $i['amount'];
				$i['price'] = $price;

				$total_price += $price;
			}
			$this->data['Sale']['price'] = $total_price;

			$this->Sale->create();
			if ($this->Sale->saveAll($this->data)) {
				$this->Session->setFlash(__('The sale has been saved', true), 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The sale could not be saved. Please, try again.', true), 'default', array('class' => 'error'));
			}
		}
		//$tables = $this->Sale->Table->getGrouped();
		$customers = $this->Sale->Customer->find('list');
		$products = $this->Sale->SaleItem->Product->getGrouped();
		$paymentTypes = $this->Sale->PaymentType->find('list');
		$this->set(compact('tables', 'customers', 'products', 'paymentTypes'));
	}

	function cancel($id = null)
	{
		return;
		if ((!$id && empty($this->data)) || ($id && !($item = $this->Sale->read(null, $id)))) {
			$this->Session->setFlash(__('Invalid Sale', true) . ($id ? " #{$id}" : ""), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}

		$this->Sale->read(null, $id);
		/*	if ($this->Sale->cancelSale($id)) {
																																																																																																																																																																																																				   $this->Session->setFlash(__('Sale canceled', true), 'default', array('class' => 'success'));
																																																																																																																																																																																																			   } else {
																																																																																																																																																																																																				   $this->Session->setFlash(__('Sale could not be canceled', true), 'default', array('class' => 'error'));
																																																																																																																																																																																																			   }*/
		//print_r($this->Sale->SaleItem);
		//die();
		foreach ($this->Sale->data['SaleItem'] as $i) {
			//print_r($i['id']);
			//die();
			$record = $this->Sale->SaleItem->find('first', array('conditions' => array('SaleItem.id' => $i[id])));
			//print_r($record);
			//die();
			unset($record['SaleItem']['id']);

			$record['SaleItem']['amount'] = -$record['SaleItem']['amount'];
			$record['SaleItem']['price'] = -$record['SaleItem']['price'];
			$this->Sale->SaleItem->create();
			//print_r($record['SaleItem']);
			//die();
			$this->Sale->SaleItem->saveAll($record['SaleItem']);


			$record = $this->Sale->SaleItem->find('first', array('conditions' => array('SaleItem.id' => $i[id])));
			//print_r($record);
			//die();
			unset($record['SaleItem']['id']);
			unset($record['SaleItem'][sale_id]);

			$this->Sale->SaleItem->create();
			//print_r($record['SaleItem']);
			//die();
			$this->Sale->SaleItem->saveAll($record['SaleItem']);


		}

		$this->redirect(array('action' => 'index'));
	}
	function cancelItem($id = null)
	{

		$record = $this->Sale->SaleItem->find('first', array('conditions' => array('SaleItem.id' => $id)));

		unset($record['SaleItem']['id']);

		$record['SaleItem']['amount'] = -$record['SaleItem']['amount'];
		$record['SaleItem']['price'] = -$record['SaleItem']['price'];
		$this->Sale->SaleItem->create();
		$this->Sale->SaleItem->saveAll($record['SaleItem']);


		$record = $this->Sale->SaleItem->find('first', array('conditions' => array('SaleItem.id' => $i[id])));
		unset($record['SaleItem']['id']);
		unset($record['SaleItem'][sale_id]);

		$this->Sale->SaleItem->create();
		$this->Sale->SaleItem->saveAll($record['SaleItem']);



		$record = $this->Sale->SaleItem->find('first', array('conditions' => array('SaleItem.id' => $id)));

		$this->redirect(array('action' => 'view', $record['SaleItem']['sale_id']));
	}
	function email($id = null)
	{
		// 1) Provjera postoji li Sale
		if (!$id || !($sale = $this->Sale->read(null, $id))) {
			$this->Session->setFlash(__('Invalid Sale', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}

		// 2) Provjera postoji li e-mail kupca
		if (empty($sale['Customer']['email'])) {
			$this->Session->setFlash(__('Kupac nema unesen e-mail.', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'view', $id));
		}

		// 3) Dohvaćanje PDF-a iz print_sale akcije
		$pdfUrl = Router::url(array(
			'controller' => 'reports',
			'action' => 'print_sale',
			$id
		), true); // Generira puni URL do print_sale akcije

		// Dohvaćanje PDF-a pomoću file_get_contents
		$pdfContent = file_get_contents($pdfUrl);
		//Dohvacanje Sale number -> broj racuna
		// $number = $this->Sale->read(null, $number);

		if ($pdfContent === false) {
			$this->Session->setFlash(__('Greška prilikom generiranja PDF-a.', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'view', $id));
		}

		// 4) Priprema za slanje e-maila
		$to = $sale['Customer']['email'];
		$subject = "Račun  #{$id}";
		$message = "Poštovani,\nU privitku se nalazi račun za Sale #{$id}.\nLP";
		$from = "prometi@itr.hr"; // prilagodite po potrebi

		$boundary = md5(time()); // jedinstveni separator multipart poruke
		$pdfBase64 = chunk_split(base64_encode($pdfContent));

		// 5) Zaglavlja
		$headers = "From: {$from}\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

		// 6) Sastavljamo multipart e-mail poruku
		$body = "--{$boundary}\r\n";
		// Dio s običnim tekstom
		$body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
		$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
		$body .= $message . "\r\n\r\n";

		// Dio s PDF privitkom
		$body .= "--{$boundary}\r\n";
		$body .= "Content-Type: application/pdf; name=\"racun_{$id}.pdf\"\r\n";
		$body .= "Content-Transfer-Encoding: base64\r\n";
		$body .= "Content-Disposition: attachment; filename=\"racun_{$id}.pdf\"\r\n\r\n";
		$body .= $pdfBase64 . "\r\n\r\n";
		$body .= "--{$boundary}--";

		// 7) Slanje e-maila
		$result = mail($to, $subject, $body, $headers);

		if ($result) {
			$this->Session->setFlash(__('Račun je uspješno poslan e-mailom.', true), 'default', array('class' => 'success'));
		} else {
			$this->Session->setFlash(__('Greška prilikom slanja e-maila.', true), 'default', array('class' => 'error'));
		}

		$this->redirect(array('action' => 'view', $id));
	}

	function testEmail()
	{
		$saleId = 5;
		$downloadPath = getenv("HOMEDRIVE") . getenv("HOMEPATH") . "C:\\Users\\Ante\\Downloads\\doc.pdf"; // Putanja do Downloads foldera za Windows 7

		if (!file_exists($downloadPath)) {
			echo "❌ PDF datoteka nije pronađena u Downloads folderu! Provjerite lokaciju: {$downloadPath}";
			exit;
		}

		$pdfContent = file_get_contents($downloadPath);

		if ($pdfContent === false) {
			echo "❌ Ne mogu učitati sadržaj PDF-a!";
			exit;
		}

		$to = 'bajunko@gmail.com';
		$subject = 'Test iz kontrolera s PDF attachmentom';
		$message = "U privitku se nalazi generirani PDF za Sale #{$saleId}.";
		$from = 'prometi@itr.hr';

		$pdfBase64 = chunk_split(base64_encode($pdfContent));
		$boundary = md5(time());

		$headers = "From: {$from}\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

		$body = "--{$boundary}\r\n";
		$body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
		$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
		$body .= $message . "\r\n\r\n";

		$body .= "--{$boundary}\r\n";
		$body .= "Content-Type: application/pdf; name=\"sale_{$saleId}.pdf\"\r\n";
		$body .= "Content-Transfer-Encoding: base64\r\n";
		$body .= "Content-Disposition: attachment; filename=\"sale_{$saleId}.pdf\"\r\n\r\n";
		$body .= $pdfBase64 . "\r\n\r\n";
		$body .= "--{$boundary}--";

		$result = mail($to, $subject, $body, $headers);

		if ($result) {
			echo "✅ Email s PDF-om poslan!<br>";

			// Brišemo PDF iz Downloads foldera nakon uspješnog slanja
			if (unlink($downloadPath)) {
				echo "✅ PDF datoteka obrisana iz Downloads foldera.";
			} else {
				echo "❌ PDF datoteka nije obrisana.";
			}
		} else {
			echo "❌ Email nije poslan. Provjerite konfiguraciju email servera.";
		}
		exit;
	}


	function testPdf()
	{
		$saleId = 5;
		$pdfUrl = "http://desktop-t3pjdpe/ugo/reports/print_sale/{$saleId}";
		$filePath = APP . "tmp/sale_{$saleId}.pdf"; // Lokacija za spremanje

		echo "⏳ Pokušaj preuzimanja PDF-a sa: {$pdfUrl}<br>";

		// 🔥 Dohvaćamo aktivni session ID
		$sessionId = $this->Session->id();
		echo "📢 Trenutni session ID: {$sessionId}<br>";

		// 🔥 1. Koristimo cURL i dodajemo session ID u kolačić
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $pdfUrl);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
		curl_setopt($ch, CURLOPT_REFERER, "http://desktop-t3pjdpe/ugo/");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Timeout ako PDF sporo generira

		// 🔥 Dodajemo sesijski kolačić da simuliramo prijavljenog korisnika
		curl_setopt($ch, CURLOPT_COOKIE, "ugo-session={$sessionId}");

		// Dohvaćanje PDF sadržaja
		$pdfContent = curl_exec($ch);
		$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$error = curl_error($ch);
		curl_close($ch);

		// 🛑 Ako i dalje dobijamo HTML umjesto PDF-a, prikažimo prvih 500 znakova odgovora
		if ($httpStatus === 200 && strpos($pdfContent, '%PDF') === false) {
			echo "❌ PDF NIJE ISPRAVNO DOHVACEN! Moguće da je vraćen HTML umjesto PDF-a.<br>";
			echo "📢 SADRŽAJ ODGOVORA (prvih 500 znakova):<br>";
			echo "<pre>" . htmlspecialchars(substr($pdfContent, 0, 500)) . "</pre>";
			exit;
		}

		// 🔥 2. Spremanje PDF-a u `tmp` folder
		file_put_contents($filePath, $pdfContent);

		if (file_exists($filePath)) {
			echo "✅ PDF uspješno spremljen u: {$filePath}<br>";
		} else {
			echo "❌ PDF nije spremljen!<br>";
		}
	}

	function savePdf()
	{
		if (!isset($_FILES['pdfFile'])) {
			echo json_encode(['success' => false, 'message' => 'Nema poslanog PDF-a.']);
			exit;
		}

		$fileTmpPath = $_FILES['pdfFile']['tmp_name'];
		$fileName = $_FILES['pdfFile']['name'];
		$destination = APP . "tmp/" . $fileName;

		if (move_uploaded_file($fileTmpPath, $destination)) {
			echo json_encode(['success' => true, 'filePath' => $destination]);
		} else {
			echo json_encode(['success' => false, 'message' => 'Greška prilikom spremanja PDF-a.']);
		}
		exit;
	}

	public function sendPdfEmail()
	{

		$saleId = isset($_GET['saleId']) ? $_GET['saleId'] : 'unknown';
		$filePath = APP . "tmp/sale_{$saleId}.pdf"; // Ispravna putanja

		error_log("🔍 sendPdfEmail() pozvana za saleId: {$saleId}");

		// 🔥 Dohvaćamo podatke o kupcu iz baze
		$sale = $this->Sale->find('first', array(
			'conditions' => array('Sale.id' => $saleId),
			'contain' => array('Customer') // Moramo učitati povezane podatke
		));

		if (!$sale) {
			error_log("❌ sendPdfEmail: Nema podatka o prodaji sa ID {$saleId}");
			echo json_encode(['success' => false, 'message' => '❌ Prodaja nije pronađena!']);
			return;
		}

		// 🔥 Provjeravamo postoji li email kupca
		if (empty($sale['Customer']['email'])) {
			error_log("❌ sendPdfEmail: Kupac nema unesen email.");
			echo json_encode(['success' => false, 'message' => '❌ Kupac nema unesen email!']);
			return;
		}

		$to = $sale['Customer']['email']; // Email kupca iz baze
		error_log("📧 Email kupca: {$to}");

		if (!file_exists($filePath)) {
			error_log("❌ sendPdfEmail: PDF nije pronađen na serveru! Path: {$filePath}");
			echo json_encode(['success' => false, 'message' => '❌ PDF nije pronađen!']);
			return;
		}

		$pdfContent = file_get_contents($filePath);
		if ($pdfContent === false) {
			error_log("❌ sendPdfEmail: Ne mogu učitati sadržaj PDF-a!");
			echo json_encode(['success' => false, 'message' => '❌ Ne mogu učitati sadržaj PDF-a!']);
			return;
		}

		$number = isset($sale['Sale']['number']) ? $sale['Sale']['number'] : null;


		$subject = "PDF za račun: #{$number}";
		$message = "Poštovani,
		 u privitku se nalazi generirani PDF za račun #{$number}.";
		$from = 'prometi@itr.hr';

		$pdfBase64 = chunk_split(base64_encode($pdfContent));
		$boundary = md5(time());

		$headers = "From: {$from}\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

		$body = "--{$boundary}\r\n";
		$body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
		$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
		$body .= $message . "\r\n\r\n";

		$body .= "--{$boundary}\r\n";
		$body .= "Content-Type: application/pdf; name=\"sale_{$number}.pdf\"\r\n";
		$body .= "Content-Transfer-Encoding: base64\r\n";
		$body .= "Content-Disposition: attachment; filename=\"sale_{$number}.pdf\"\r\n\r\n";
		$body .= $pdfBase64 . "\r\n\r\n";
		$body .= "--{$boundary}--";

		// 🔥 Slanje emaila
		$result = mail($to, $subject, $body, $headers);

		if ($result) {
			unlink($filePath); // Brišemo PDF nakon slanja
			error_log("✅ sendPdfEmail: Email s PDF-om poslan na {$to}");
			echo json_encode(['success' => true, 'message' => '✅ Email s PDF-om poslan kupcu!']);
		} else {
			error_log("❌ sendPdfEmail: Email NIJE poslan! Provjerite mail server.");
			echo json_encode(['success' => false, 'message' => '❌ Email nije poslan! Provjerite mail server.']);
		}
		return;
	}




	function _faCustomers()
	{
		return $this->Sale->Customer->find('list');
	}

	/**
	 * Pošalji račun emailom - analogno ponudama
	 */
	function send_email($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Nevažeći račun', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}

		// Dohvati račun s podacima o kupcu
		$this->Sale->contain('Customer', 'PaymentType');
		$sale = $this->Sale->read(null, $id);
		
		if (empty($sale)) {
			$this->Session->setFlash(__('Račun nije pronađen', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}

		$this->set('sale', $sale);
		$this->set('sale_id', $id);
	}

}
