<?php
use Joomla\CMS\Factory;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Filesystem\File;
/**
 * @version        5.6.0
 * @package        Joomla
 * @subpackage     Joom Donation
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2009 - 2023 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die;

class DonationModelImport extends OSFModel
{
	/**
	 * @param $input
	 *
	 * @return int
	 * @throws Exception
	 */
	public function store($input)
	{
		$db        = Factory::getDbo();
		$query     = $db->getQuery(true);
		$donors    = $this->getDonorsFromCSVFile($input);
		$todayDate = Factory::getDate()->toSql();

		if (count($donors))
		{
			$imported = 0;
			foreach ($donors as $donor)
			{
				if (empty($donor['first_name']))
				{
					continue;
				}

				if (!empty($donor['campaign']))
				{
					$query->clear()
						->select('id')
						->from('#__jd_campaigns')
						->where('title = ' . $db->quote($donor['campaign']));
					$db->setQuery($query);
					$donor['campaign_id'] = (int) $db->loadResult();
				}

				$row = Table::getInstance('donor', 'DonationTable');
				if (!empty($donor['created_date']) && strtotime($donor['created_date']) !== false)
				{
					$donor ['created_date'] = Factory::getDate($donor ['created_date'])->toSql();
				}
				else
				{
					$donor ['created_date'] = $todayDate;
				}

				if (!empty($donor['email']))
				{
					$query->clear()
						->select('id')
						->from('#__users')
						->where('email = ' . $db->quote($donor['email']));
					$db->setQuery($query);
					$donor['user_id'] = (int) $db->loadResult();
				}
				$donor['mollie_recurring_start_date'] = "0000-00-00 00:00:00";
				$row->bind($donor);

				if (!$row->store()) 
				{
					//JError::raiseError(500, $row->getError() );
					throw new Exception($row->getError(), 500);
				}

				$imported++;
			}
		}

		return $imported;
	}

	/**
	 * Get subscribers data from csv file
	 *
	 * @param $input
	 *
	 * @return array
	 */
	protected function getDonorsFromCSVFile($input)
	{
		$keys        = array();
		$donors      = array();
		$donor       = array();
		$allowedExts = array('csv');
		$csvFile     = $input->files->get('csv_donors');
		$csvFileName = $csvFile['tmp_name'];
		$fileName    = $csvFile['name'];
		$fileExt     = strtolower(File::getExt($fileName));
		if (in_array($fileExt, $allowedExts))
		{
			$line = 0;
			$fp   = fopen($csvFileName, 'r');
			$i = 0;
			while (($cells = fgetcsv($fp, 0, ",")) !== false)
			{
				$i++;
				//print_r($cells);
				//echo "<BR />";
				if ($line == 0)
				{
					foreach ($cells as $key)
					{
						$keys[] = $key;
					}
					$line++;
				}
				else
				{
					$i = 0;
					foreach ($cells as $cell)
					{
						$donor[$keys[$i]] = $cell;
						$i++;
					}
					$donors[] = $donor;
				}
			}
			//die();
			fclose($fp);
		}

		return $donors;
	}
}
