<?php

add_filter('gform_addon_navigation', 'add_menu_item');
function add_menu_item($menu_items)
{
	$menu_items[] = array("name" => "Homegrade Stats", "label" => "Homegrade Datas", "callback" => "homegrade_stats_option_page", "permission" => "edit_posts");
	return $menu_items;
}



function homegrade_stats_option_page()
{
?>
	<div class="wrap  ">
		<h1>Exports de données Homegrade</h1>

		<div class="homegrade-data-exports-page">

			<div class="card export-card">
				<h2>Formulaire de commande <br />des brochures papier</h2>
				<img class="export-card__illustration" src="<?php echo get_template_directory_uri() . '/resources/img/illustrations/homegrade_formations-peb.svg' ?>" alt="">
				<form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
					<input type="hidden" name="action" value="export_paper_order_datas">
					<input type="hidden" name="export_paper_order_datas_nonce" value="<?php echo wp_create_nonce('export_paper_order_datas_nonce'); ?>">
					<button type="submit" name="custom_action_button" class="button button-primary">
						<?php echo __("Exporter les données", "homegrade-theme__texte-fonctionnel"); ?>
					</button>
				</form>
			</div>
		</div>
	</div>
<?php
}

add_action('admin_post_export_paper_order_datas', 'handle_download_pdf_request');

function handle_download_pdf_request()
{
	// Vérifier la nonce pour des raisons de sécurité
	if (!isset($_POST['export_paper_order_datas_nonce']) || !wp_verify_nonce($_POST['export_paper_order_datas_nonce'], 'export_paper_order_datas_nonce') || !current_user_can('read')) {
		wp_die('Vérification de sécurité échouée.');
	}

	generate_order_datas_to_csv();
	exit;
}

function generate_order_datas_to_csv()
{
	$form_id = 18;


	$search_criteria = array("status" => "active");
	$sorting         = array();
	$paging = array(
		'offset'    => 0,
		'page_size' => 9000,
	);
	$entries = GFAPI::get_entries($form_id, $search_criteria, $sorting, $paging);



	if (is_wp_error($entries)) {
		wp_die('Erreur lors de la récupération des données du formulaire.');
	}

	$output_formatted_entries = array();


	foreach ($entries as $key => $entry) {

		// $clientFirstName = $entry['3'];
		// $clientLastName = $entry['2'];
		$companyType = $entry['7'];
		$zipCode = $entry['9.5'];
		$userLanguage = strtoupper($entry['27']) ?? null;

		$synthesePrimes = isset($entry['24']) ? unserialize($entry['24']) : [];
		$brochures = isset($entry['25']) ? unserialize($entry['25']) : [];
		$autrePublications = isset($entry['26']) ? unserialize($entry['26']) : [];

		$explodedEntryDocuments = array_merge($synthesePrimes, $brochures, $autrePublications);


		foreach ($explodedEntryDocuments as $key => $document) {
			$document_id_fr = $document['id_fr'] ?? null;
			$document_quantity_fr = $document['quantity_fr'] ?? null;

			$document_id_nl = $document['id_nl'] ?? null;
			$document_quantity_nl = $document['quantity_nl'] ?? null;

			$dateCreatedRaw = $entry['date_created'] ?? '';
			$dateCreated = $dateCreatedRaw ? date('d / m / Y', strtotime($dateCreatedRaw)) : '';

			if (!$document_quantity_fr && !$document_quantity_nl) {
				continue;
			}

			if ($document_quantity_nl) {
				$thematique = getPostMainThematique($document_id_nl)->name ?? '';
				$document_formatted_order_nl = [
					'publication' => $document_id_nl ? get_the_title($document_id_nl) : $key,
					'quantity' => $document_quantity_nl,
					'document_language' => 'NL',
					'thematique' => $thematique,
					'brochureID' => $document_id_nl,
					'company_type' => $companyType,
					'zipCode' => $zipCode,
					'userLanguage' => $userLanguage,
					'order_date' => $dateCreated,
				];
				array_push($output_formatted_entries, $document_formatted_order_nl);
			}

			if ($document_quantity_fr) {
				$thematique = getPostMainThematique($document_id_fr)->name ?? '';

				$document_formatted_order_fr = [
					'publication' => $document_id_fr ? get_the_title($document_id_fr) : $key,
					'quantity' => $document_quantity_fr,
					'document_language' => 'FR',
					'thematique' => $thematique,
					'brochureID' => $document_id_fr,
					'company_type' => $companyType,
					'zipCode' => $zipCode,
					'userLanguage' => $userLanguage,
					'order_date' => $dateCreated,
				];
				array_push($output_formatted_entries, $document_formatted_order_fr);
			}
		}
	}

	// Définir le nom du fichier CSV
	$filename = 'order_data_' . date('Ymd_His') . '.csv';

	// Ouvrir un fichier CSV en mode écriture
	$file = fopen($filename, 'w');

	if ($file === false) {
		wp_die('Erreur lors de la création du fichier CSV.');
	}

	// Ajouter les en-têtes du CSV
	fputcsv($file, ['Publication', 'Quantité', 'Langue de la publication', 'Thématique', 'ID de la brochure', 'Type d\'organisme', 'Code Postal', 'Langue de l\'utilisateur', 'Date de la commande']);

	// Boucler sur chaque entrée formatée et l'écrire dans le CSV
	foreach ($output_formatted_entries as $entry) {
		fputcsv($file, $entry);
	}

	// Fermer le fichier
	fclose($file);

	// Télécharger le fichier CSV
	header('Content-Type: text/csv');
	header('Content-Disposition: attachment;filename="' . $filename . '"');
	readfile($filename);

	// Supprimer le fichier après téléchargement
	unlink($filename);

	exit();
}
