<?php

if (!defined('ABSPATH')) exit;  // Exit if accessed directly

global $wpdb;

$setting_table 	= $wpdb->prefix . 'giftvouchers_setting';
$setting_options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");
$items = isset($_GET['items']) ? $_GET['items'] : '';
$wcproductorder = isset($_GET['wcproductorder']) ? $_GET['wcproductorder'] : '';
$tab = isset($_GET['tab']) ? $_GET['tab'] : '';
$voucher_code = isset($_GET['voucher_code']) ? $_GET['voucher_code'] : '';


if (isset($_FILES['import_file']) && current_user_can('manage_options')) {

	$file = $_FILES['import_file'];

	if ($file['error'] === 0 && pathinfo($file['name'], PATHINFO_EXTENSION) === 'json') {
		$json_data = file_get_contents($file['tmp_name']);
		$data = json_decode($json_data, true);

		if (!is_array($data)) {
			wp_die(__('Invalid JSON file.', 'gift-voucher'));
		}

		$table1 = $wpdb->prefix . 'giftvouchers_list';
		$table2 = $wpdb->prefix . 'giftvouchers_activity';

		// Optional: Clear current data if needed
		// $wpdb->query("DELETE FROM {$table1}");
		// $wpdb->query("DELETE FROM {$table2}");

		if (!empty($data['giftvouchers_list'])) {
			foreach ($data['giftvouchers_list'] as $row) {
				$wpdb->insert($table1, $row);
			}
		}

		if (!empty($data['giftvouchers_activity'])) {
			foreach ($data['giftvouchers_activity'] as $row) {
				$wpdb->insert($table2, $row);
			}
		}

		echo '<div class="notice notice-success is-dismissible"><p>' . __('Database imported successfully.', 'gift-voucher') . '</p></div>';
	} else {
		echo '<div class="notice notice-error is-dismissible"><p>' . __('Failed to import database. Please upload a valid .json file.', 'gift-voucher') . '</p></div>';
	}
}

?>
<div class="wrap voucher-page">
	<h1><?php echo __('Purchase History', 'gift-voucher') ?></h1><br>
	<div class="content">
		<?php
		$sql = "SELECT id, amount FROM {$wpdb->prefix}giftvouchers_list WHERE `status` = 'unused' AND `payment_status` = 'Paid' ORDER BY `id` DESC";
		$orders = $wpdb->get_results($sql, ARRAY_A);
		$columns = array();
		$amount = 0;
		foreach ($orders as $row) {
			$columns[] = $row['id'];
			$amount += $row['amount'];
		}
		do_wpgv_check_voucher_status();
		$num_fields = count($columns);
		if ($num_fields > 0) { ?>
			<div class="total-unused">
				<div class="count">
					<span><?php echo $num_fields ?></span><?php echo __('Unused GiftCard', 'gift-voucher'); ?>
				</div>
				<div class="amount">
					<span><?php echo wpgv_price_format($amount) ?></span><?php echo __('Total Unused GiftCard Amount', 'gift-voucher'); ?>
				</div>
				<form action="<?php echo admin_url('admin.php'); ?>">
					<input type="hidden" name="page" value="vouchers-lists">
					<?php if ($wcproductorder) : ?><input type="hidden" name="wcproductorder" value="1"><?php endif; ?>
					<?php if ($items) : ?><input type="hidden" name="items" value="1"><?php endif; ?>
					<input type="hidden" name="search" value="1">
					<input type="text" name="voucher_code" autocomplete="off" placeholder="Search by Gift voucher code or email" value="<?php echo $voucher_code ?>" style="width: 300px;">
					<input type="submit" class="button button-primary" value="Search">
				</form>
			</div>
		<?php } ?>
		<?php //$this->export_orders();
		?>
		<h2 class="nav-tab-wrapper">
			<a class="nav-tab <?php if (!$items && $tab != "import-order" && !isset($_GET['items']) && !$wcproductorder) : ?>nav-tab-active<?php endif; ?>" href="?page=vouchers-lists">
				<?php echo __('All gift cards', 'gift-voucher') ?>
			</a>
			<a class="nav-tab <?php if ($wcproductorder && $tab != "import-order") : ?>nav-tab-active<?php endif; ?>" href="?page=vouchers-lists&wcproductorder=1">
				<?php echo __('Purchased Giftcard Products', 'gift-voucher') ?>
			</a>
			<a class="nav-tab <?php if ($tab == "new-order") : ?>nav-tab-active<?php endif; ?>" href="?page=add-gift-voucher-order">
				<?php echo __('Add New Giftcard Order', 'gift-voucher') ?>
			</a>
			<a class="nav-tab" href="?page=export_voucher_order">
				<?php echo __('Export as CSV', 'gift-voucher') ?>
			</a>
			<a class="nav-tab" href="?page=export_giftcard_db">
				<?php echo __('Export Database', 'gift-voucher'); ?>
			</a>
			<a class="nav-tab" id="import_giftcard_db" href="?page=import_giftcard_db">
				<?php echo __('Import Database', 'gift-voucher'); ?>
			</a>
		</h2>
		<div id="post-body" class="metabox-holder">
			<div id="upload_section" style="display:none;margin: 20px 0;">
				<form method="post" enctype="multipart/form-data" style="width:25%;margin:auto;border: 1px solid #c3c4c7;background: #fff;padding:20px;display:flex" onsubmit="return validateJSONUpload()">
					<input type="file" name="import_file" id="import_file" accept="application/json" />
					<input type="submit" value="Import" class="button button-primary" id="import_button" disabled />
				</form>
			</div>
			<div id="post-body-content">
				<div class="meta-box-sortables ui-sortable">
					<div <?php if ($tab == "import-order") { ?> style="display:none;" <?php } ?>>
						<form method="post">
							<?php
							$this->vouchers_obj->prepare_items();
							$this->vouchers_obj->display();
							?>
						</form>
					</div>
					<div <?php if ($tab == "import-order") { ?> style="display:block;" <?php } else { ?> style="display:none;" <?php } ?>>
						<?php
						if (isset($_GET["msg"])) {
							if ($_GET["msg"] == "1") {
								echo "<br><b style='color:red;'>Please Select CSV File</b><br>";
							} else if ($_GET["msg"] == "2") {

								echo "<br> <b style='color:#46b450;'>" . $_GET["import"] . " Order Imported Successfully </b><br>";
							} else if ($_GET["msg"] == "3") {

								echo "<br><b style='color:red;'>Please Select Valid CSV File</b><br>";
							}
						}
						?>
						<br>
						<form method="post" action="<?php echo admin_url("admin.php"); ?>?page=import_voucher_order" enctype='multipart/form-data'>
							<input type="file" name="voucher_oreder_import_file"><br>
							<input type="submit" value="Import" name="voucher_oreder_import_btn" class="btn button-primary" id="voucher_oreder_import_btn">
						</form>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
	document.addEventListener('DOMContentLoaded', function() {
		const fileInput = document.getElementById('import_file');
		const importButton = document.getElementById('import_button');

		fileInput.addEventListener('change', function() {
			const file = this.files[0];
			if (file && file.name.endsWith('.json')) {
				importButton.disabled = false;
			} else {
				importButton.disabled = true;
				alert('Please upload a valid .json file.');
			}
		});
	});

	function validateJSONUpload() {
		const fileInput = document.getElementById('import_file');
		const file = fileInput.files[0];
		if (!file || !file.name.endsWith('.json')) {
			alert('Please select a valid .json file to import.');
			return false;
		}
		return true;
	}
	jQuery(document).ready(function($) {
		$('#import_giftcard_db').on('click', function(e) {
			e.preventDefault();
			$('#upload_section').stop(true, true).slideToggle('fast');
		});
	});
</script>