<?php

namespace MyApp;

use PP\Models\Donation;

/**
 * Creates a new donation
 * Requires data to be passed by $_POST
 */
class DonationFactory  {

    /**
     * Creates a new donation object
     * Requires data to be passed through $_POST
     * @return  Donation the donation object
     */
    public static function create() 
    {
        // validate fields
        static::validateFields();
        $d = new Donation;
        $d->setAmount($_POST['amount']);
        $d->setCurrency("usd");
        $d->setSource($_POST['source']);
        $d->setReceiptEmail($_POST['email']);
        $d->setPlatformFee(0); // @todo replace this with a value you wish to set
        $d->setDestinationEIN($_POST['charity-ein']);
        return $d;
    }    


    /**
     * Validates Fields sent from front-end
     * Relies heavily on $_POST
     * @throws \Exception on update error or invalid security options
     * @return void;
     */
    private static function validateFields() {

    	// hidden fields first
    	if (empty($_POST['source'])) {
		    throw new \Exception( 'A system error occurred (\'source\' is not provided). Please try again later.' );
	    }

    	// next email field
        if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_SANITIZE_EMAIL)) {
    		var_dump($_POST);
            throw new \InvalidArgumentException('Please ensure you have provided a valid email address.');
        }

        // validate the amount
        $amt = $_POST['amount'] ?? 0;
        if (empty($amt)) {
	        throw new \InvalidArgumentException( 'Please ensure you have specified a donation amount.' );
        }

        $amt = str_replace("$", "", $amt);
        if (!preg_match('/^[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$/', $amt)) {
	        throw new \InvalidArgumentException( 'Enter your donation amount as a whole number, no decimal points nor commas.' );
        }

	    $amt = str_replace(".", "", $amt);
	    $amt = str_replace(",", "", $amt);
	    $amt = str_replace(" ", "", $amt);
	    $_POST['amount'] = $amt;

	    $_POST['charity-ein'] = $_POST['charity-ein'] ?? null;
    }
}
