<?php
function initSessionData() {
	$rise = (int) $_POST['rise'];

	switch ( $_POST['target_slope'] ) {
		case '18':
			$total_rise              = $rise * 18 - 32;
			$slope_ratio = 2.66666;
			break;

		case '15':
			$total_rise              = $rise * 15 - 32;
			$slope_ratio = 3.2;
			break;

		case '12':
			$total_rise              = $rise * 12 - 32;
			$slope_ratio = 4;
			break;

		case '9':
			$total_rise              = $rise * 9 - 32;
			$slope_ratio = 5.33333;
			break;

		case '6':
			$total_rise              = $rise * 6 - 32;
			$slope_ratio = 8;
			break;

		case '3':
			$total_rise              = $rise * 3 - 32;
			$slope_ratio = 16;
			break;
		default:
			$slope_ratio  = false;
			break;
	}

    $_SESSION['uuid']         = uniqid();
	$_SESSION['target_rise']  = $rise;
	$_SESSION['rise']         = $rise;
	$_SESSION['target_slope'] = $_POST['target_slope'];
	$_SESSION['slope_ratio']  = $slope_ratio;
	$_SESSION['total_rise']   = $total_rise;
    $_SESSION['ada_compliant'] = !empty($_POST['ada_compliant']);
    $_SESSION['designed_by']  = null;
    $_SESSION['project_num']  = null;
    $_SESSION['email']        = null;
    $_SESSION['notes']        = null;
    $_SESSION['country']      = null;
    $_SESSION['state']        = null;
    $_SESSION['is_dealer']    = false;

	// Why /12/4?  // Ask QRamp peeps the math for this.
	$_SESSION['num_mods']   = ceil( $total_rise / 12 / 4 );

}

function saveProjectDetails($session) {
	if(!is_array($session) OR empty($session)) return;

	$file_txt = UPLOAD_DIR . $session['filename'].'.txt';

	$data = [
		'Designed On: ' => date( 'M d,Y' ),
		'Designed By: ' => $session['designed_by'],
		'Project Number: ' => $session['project_num'],
		'Reference Number: ' => $session['filename'],
		'Email: ' => $session['email'],
		'Notes: ' => $session['notes'],
		'Actual Slope: ' => $session['actual_slope'],
		'Target Slope: ' => $session['target_slope'],
		'Rise: ' => $session['rise'],
		'Modules: ' => stringifyModules($session['mcount'])
	];

	$content = "";
	foreach($data as $key => $value) {
		$content .= "{$key} {$value} \r\n";
	}

//	dd($content, $_POST, $session, $data);
	file_put_contents($file_txt, $content);

	return;

}

function stringifyModules($modules) {
	$string = '';
	foreach($modules as $mod => $count) {
		if($count) {
			$string .= "{$mod}: {$count}, ";
		}
	}
	return $string;
}

/**
 * $image image cursor (from imagecreatetruecolor)
 * $backgound image curosr (from imagecolorallocate)
 * $paddng int
 */
function cropImage( $image, $background = false, $padding = 0 ) {
	if ( $background ) {
		$background = imagecolorallocate( $image, 255, 255, 255 );
	}

	$top    = imageSY( $image );
	$left   = imageSX( $image );
	$bottom = 0;
	$right  = 0;

	for ( $x = 0; $x < imagesx( $image ); $x ++ ) {
		for ( $y = 0; $y < imagesy( $image ); $y ++ ) {

			// if there match
			if ( imagecolorat( $image, $x, $y ) != $background ) {

				if ( $x < $left ) {
					$left = $x;
				}
				if ( $x > $right ) {
					$right = $x;
				}
				if ( $y > $bottom ) {
					$bottom = $y;
				}
				if ( $y < $top ) {
					$top = $y;
				}
			}
		}
	}

	$right ++;
	$bottom ++;

	// create new image with padding
	$img = imagecreatetruecolor( $right - $left + $padding * 2, $bottom - $top + $padding * 2 );
	// fill the background
	imagefill( $img, 0, 0, $background );
	// copy
	imagecopy( $img, $image, $padding, $padding, $left, $top, $right - $left, $bottom - $top );

	// destroy old image cursor
	imagedestroy( $image );

	return $img;
}

/**
 * Converts a base64 string to a png file
 *
 * @param string $base64String
 * @param string $filename
 *
 * @return void
 */
function base64StringToPng($base64String, $filename) {
    // Split the base64 encoded string
    $imageBase = explode(',', $base64String);
    $imageData = $imageBase[1];

    // Decode from base64
    $image = base64_decode($imageData);

    // Create a file
    $file = fopen($filename, 'w');
    fwrite($file, $image);
    fclose($file);

    // Create a new image from the file
    $png = imagecreatefrompng($filename);

    // Set white background to transparent
    $white = imagecolorallocate($png, 255, 255, 255);
    imagecolortransparent($png, $white);

    // Trim out the transparent background
    $cropped = cropImage($png, true);

    // Get dimensions of the cropped image
    $width = imagesx($cropped);
    $height = imagesy($cropped);

    // Set max dimensions of the PDF
    $maxWidth = 980;
    $maxHeight = 646;

    // Calculate aspect ratio and resize if necessary
    if ($width > $maxWidth || $height > $maxHeight) {
        // Determine scaling factor
        $ratio = min($maxWidth / $width, $maxHeight / $height);
        $newWidth = $width * $ratio;
        $newHeight = $height * $ratio;

        // Create a new true color image
        $resized = imagecreatetruecolor($newWidth, $newHeight);

        // Copy and resize the cropped image to the new image
        imagecopyresampled($resized, $cropped, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

        // Clean up the original cropped image
        imagedestroy($cropped);

        // Replace the cropped image with the resized version
        $cropped = $resized;
    }

    // Save the image
    imagepng($cropped, $filename);

    // Clean up
    imagedestroy($cropped);
}

function createProjectPdf() {
    $pdf = Zend_Pdf::load(ROOT_DIR . '/assets/pdf/project.pdf');

	// Set up the document.
	$string         = "";
	$pdf_filename   = '';
	$name_details_y = 0;
	$page_num       = 0; // First page
	$page           = $pdf->pages[$page_num];
	$template       = clone $pdf->pages[$page_num]; // cloning the page (a must do)

	$refNumber  = $_SESSION['uuid'] ?? 'Unknown';
	$monthDir   = date('Y-m');
	$projectDir = UPLOAD_DIR . $monthDir;
	$fileSlug   = slugify($_SESSION['project_num'] ?? 'project') . '-' . date('Y-m-d');

	if (!is_dir($projectDir)) {
		mkdir($projectDir, 0755, true);
	}

	$oldPng = UPLOAD_DIR . $refNumber . '.png';
	$newPng = "{$projectDir}/{$fileSlug}.png";
	if (file_exists($oldPng)) {
		rename($oldPng, $newPng);
	}

	$pdf_filename = "{$monthDir}/{$fileSlug}";

	// Set font
	$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 8);

	// Set stage for main ramp image
	$image = Zend_Pdf_Image::imageWithPath($newPng);

	$imgWidthPts  = $image->getPixelWidth() * 72 / 96;
	$imgHeightPts = $image->getPixelHeight() * 72 / 96;

	$x1 = ($page->getWidth() - $imgWidthPts) / 2;
	$y1 = 120;

	// Draw image
	$page->drawImage($image, $x1, $y1, $x1 + $imgWidthPts, $y1 + $imgHeightPts);

	// Draw text on screen
	$string = (strlen($_SESSION['notes']) > 48) ? substr($_SESSION['notes'], 0, 45) . '...' : $_SESSION['notes'];
	$page->drawText($string, 590, 75);
	$page->drawText($_SESSION['project_num'], 690, 44);
	$page->drawText($_SESSION['designed_by'], 545, 35);
	$page->drawText($_SESSION['email'], 600, $name_details_y -= 10);
	$page->drawText($refNumber, 700, 30); // Reference number
	$page->drawText(date('M d,Y'), 475, 35);

	// Draw in the module counts
	$x_value = 45;
	$y_value = 80;
	$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD), 12);

	$num_diff_modules = 0;
	foreach ($_SESSION['mcount'] as $k => $v) {
		if ($v > 0) {
			$num_diff_modules += 1;
			if ($num_diff_modules > 3) {
				$num_diff_modules = 1;
				$x_value          += 50;
				$y_value          = 80;
			}
			$page->drawText($k . ": " . $v, $x_value -= 0, $y_value -= 12);
		}
	}

	// Add in the slope ratio diagram
	$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 8);

	if ($_SESSION['actual_slope'] >= 5 && $_SESSION['actual_slope'] <= 7.5) {
		$ramp_image = "1-6.jpg";
	} else if ($_SESSION['actual_slope'] >= 7.5 && $_SESSION['actual_slope'] <= 10.5) {
		$ramp_image = "1-9.jpg";
	} else if ($_SESSION['actual_slope'] >= 10.5 && $_SESSION['actual_slope'] <= 13.5) {
		$ramp_image = "1-12.jpg";
	} else if ($_SESSION['actual_slope'] >= 13.5 && $_SESSION['actual_slope'] <= 17.5) {
		$ramp_image = "1-15.jpg";
	} else if ($_SESSION['actual_slope'] >= 17.5 && $_SESSION['actual_slope'] <= 19.5) {
		$ramp_image = "1-18.jpg";
	} else {
		$ramp_image = false;
	}

	if ($ramp_image) {
		$path      = "images/slopes/";
		$imagePath = $path . $ramp_image;
		//$page->drawText($imagePath, 80, 100);

		// Load image
		$image  = Zend_Pdf_Image::imageWithPath($imagePath);
		$left   = 275;
		$bottom = 30;
		$right  = 425;
		$top    = 74;

		// Draw image
		$page->drawImage($image, $left, $bottom, $right, $top);
	} else {
		$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD), 14);
		$page->drawText("Sample Image Not Available", 235, 45);
	}

	// Add in the slope information
	$slope = $_SESSION['target_slope'];
	$rise  = $_SESSION['rise'];

	$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 8);
	$page->drawText("1:" . $slope, 400, 85);
	$page->drawText($rise . '"', 270, 85);
	$page->drawText("1:" . $_SESSION['actual_slope'], 262, 72);

	// Create the pdf
	$_SESSION['pdf_filname'] = $fileSlug . ".pdf";
	$pdf->save(UPLOAD_DIR . $pdf_filename . ".pdf");
}

function sendEmail(
    $to = ['sites@abstractmarketing.ca' => 'QRamp Designer'],
    $subject = 'Message from QRamp Builder',
    $body = '',
    $attachments = null
) {
    if (defined('EMAIL') && !EMAIL) return;

    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    if (defined('DEBUG') && DEBUG) {
        $to = ['lancehammondam@gmail.com' => 'QRamp Sales'];
    }

    try {
        $mail->isSMTP();
        $mail->Host       = 'build.qramp.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'noreply@build.qramp.com';
        $mail->Password   = 'ih$@%BXbhE@r';
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('noreply@build.qramp.com', 'QRamp Builder');

        // Recipients
        foreach ($to as $email => $name) {
            if (!defined('DEBUG')) {
                $mail->addAddress($email, $name);
            }
        }

        // Attachments
        if (is_array($attachments)) {
            foreach ($attachments as $file => $label) {
                $mail->addAttachment($file, $label);
            }
        }

        // Content
        $mail->Subject = $subject;
        $mail->isHTML(true);
        $mail->Body = $body;
        $mail->AltBody = stripHtmlTags($body);
        $mail->send();
    } catch (PHPMailer\PHPMailer\Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}

function stripHtmlTags($string) {
    $string = html_entity_decode($string, ENT_QUOTES);
    return preg_replace('/<[^>]*>/', '', $string);
}

function slugify($text) {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    return trim($text, '-') ?: 'project';
}

function sanitizeTextField($text) {
    // Remove any HTML tags
    $text = strip_tags($text);

    // Remove any special characters
    $text = preg_replace('/[^A-Za-z0-9\-\. ]/', '', $text);

    // Replace any multiple spaces with a single space
    $text = preg_replace('/\s+/', ' ', $text);

    // Trim any leading or trailing spaces
    $text = trim($text);

    return $text;
}

function sanitizeTextareaField($text) {
    // Remove any HTML tags
    $text = strip_tags($text);

    // Convert special characters to HTML entities
    $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');

    // Trim any leading or trailing spaces
    $text = trim($text);

    return $text;
}

function sanitizeEmailField($email) {
    // Remove any non-alphanumeric characters from the email
    $sanitized = preg_replace('/[^a-zA-Z0-9@._%+-]/', '', $email);

    // Validate the sanitized string as an email using PHP's filter_var function
    if (filter_var($sanitized, FILTER_VALIDATE_EMAIL)) {
        return true;
    }

    return false;
}
