<?php echo message_box('success'); ?>
<?php
$lang_options = array();
if (!empty($languages)) {
	foreach ($languages as $lang) {
		$lang_options[$lang->name] = ucfirst($lang->name);
	}
}
$locale_options = array();
if (!empty($locales)) {
	foreach ($locales as $loc) {
		$locale_options[$loc->locale] = $loc->name;
	}
}
$timezone_options = !empty($timezones) ? $timezones : array();
$currency_options = array();
if (!empty($currencies)) {
	foreach ($currencies as $cur) {
		$currency_options[$cur->code] = $cur->name;
	}
}
$payment_method_options = array('0' => lang('select_payment_method'));
$payment_methods = $this->db->order_by('payment_methods_id', 'DESC')->get('tbl_payment_methods')->result();
if (!empty($payment_methods)) {
	foreach ($payment_methods as $p_method) {
		$payment_method_options[$p_method->payment_methods_id] = $p_method->method_name;
	}
}
$attendance_report_options = array(
	'1' => lang('attendance_report') . ' 1',
	'2' => lang('attendance_report') . ' 2',
	'3' => lang('attendance_report') . ' 3',
	'4' => lang('attendance_report') . ' 4',
	'5' => lang('attendance_report') . ' 5',
	'6' => lang('attendance_report') . ' 6',
	'7' => lang('attendance_report') . ' 7',
);
$project_view_options = array('1' => lang('project_details_view') . ' 1', '2' => lang('project_details_view') . ' 2');
$task_view_options = array('1' => lang('task_details_view') . ' 1', '2' => lang('task_details_view') . ' 2');
$activity_style_options = array(
	'timeline' => 'Timeline',
	'feed' => 'Feed',
	'cards' => 'Cards',
	'stacked' => 'Stacked',
	'compact' => 'Compact',
);
$currency_position_options = array('1' => "$ 100", '2' => "100 $");
$this->settings_model->set_locale();
$date_format = config_item('date_format');
$date_format_options = array(
	'%d-%m-%Y' => ci_format_datetime(time(), '%d-%m-%Y', true),
	'%m-%d-%Y' => ci_format_datetime(time(), '%m-%d-%Y', true),
	'%Y-%m-%d' => ci_format_datetime(time(), '%Y-%m-%d', true),
	'%d-%m-%y' => ci_format_datetime(time(), '%d-%m-%y', true),
	'%m-%d-%y' => ci_format_datetime(time(), '%m-%d-%y', true),
	'%m.%d.%Y' => ci_format_datetime(time(), '%m.%d.%Y', true),
	'%d.%m.%Y' => ci_format_datetime(time(), '%d.%m.%Y', true),
	'%Y.%m.%d' => ci_format_datetime(time(), '%Y.%m.%d', true),
);
$time_format_options = array(
	'g:i a' => date('g:i a'),
	'g:i A' => date('g:i A'),
	'H:i' => date('H:i'),
);
if (empty(config_item('decimal_separator'))) {
	$decimal_separator = 2;
} else {
	$decimal_separator = config_item('decimal_separator');
}
$decimal = sprintf('%0' . $decimal_separator . 'd', 0);
$money_format_options = array(
	'1' => "1,234." . $decimal,
	'2' => "1.234," . $decimal,
	'3' => "1234." . $decimal,
	'4' => "1234," . $decimal,
	'5' => "1'234." . $decimal,
	'6' => "1 234." . $decimal,
	'7' => "1 234," . $decimal,
	'8' => "1 234'" . $decimal,
);
$client_menu_options = array();
$all_client_menu = $this->db->where('parent', 0)->order_by('sort')->get('tbl_client_menu')->result();
if (!empty($all_client_menu)) {
	foreach ($all_client_menu as $v_client_menu) {
		if ($v_client_menu->label != 'dashboard') {
			$client_menu_options[$v_client_menu->menu_id] = lang($v_client_menu->label);
		}
	}
}
$client_menu_selected = array();
$client_menu = unserialize(config_item('client_default_menu'));
if (!empty($client_menu['client_default_menu'])) {
	$client_menu_selected = $client_menu['client_default_menu'];
}
$client_menu_selected_items = array();
if (!empty($all_client_menu) && !empty($client_menu_selected)) {
	foreach ($all_client_menu as $v_client_menu) {
		if (in_array($v_client_menu->menu_id, $client_menu_selected)) {
			$client_menu_selected_items[] = array(
				'id' => $v_client_menu->menu_id,
				'text' => lang($v_client_menu->label),
			);
		}
	}
}
$selected_default_account_label = '';
if (!empty(config_item('default_account'))) {
	$default_account_info = $this->db->select('account_name')
		->where('account_id', config_item('default_account'))
		->get('tbl_accounts')
		->row();
	if (!empty($default_account_info->account_name)) {
		$selected_default_account_label = $default_account_info->account_name;
	}
}
$acreated = can_action('36', 'created');
?>

<div class="space-y-6">
	<form role="form" id="form" action="<?php echo base_url(); ?>admin/settings/save_system" method="post"
		class="space-y-6">
		<div class="rounded-2xl border border-border bg-card shadow-sm">
			<div class="flex items-center justify-between border-b border-border px-6 py-4">
				<div>
					<h3 class="text-lg font-semibold text-foreground"><?= lang('system_settings') ?></h3>
					<p class="text-sm text-muted-foreground"><?= lang('manage') . ' ' . lang('system_settings') ?></p>
				</div>
				<button type="submit" class="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-6 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition hover:bg-primary/90">
					<i data-lucide="save" class="h-4 w-4"></i>
					<?= lang('save_changes') ?>
				</button>
			</div>
			<div class="p-6">
				<?php if (validation_errors()) { ?>
					<div class="rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700 dark:border-rose-900/40 dark:bg-rose-900/20 dark:text-rose-300">
						<?= validation_errors(); ?>
					</div>
				<?php } ?>
				<input type="hidden" name="settings" value="<?= $load_setting ?>">

				<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
					<div class="space-y-4">
						<?= form_select_group('default_language', lang('default_language'), $lang_options, config_item('default_language'), false, array('class' => 'select_box')); ?>
						<?= form_select_group('locale', lang('locale'), $locale_options, config_item('locale'), true, array('class' => 'select_box')); ?>
						<?= form_select_group('timezone', lang('timezone'), $timezone_options, config_item('timezone'), true, array('class' => 'select_box')); ?>

						<div class="flex items-end gap-2">
							<div class="flex-1">
								<?= form_select_group('default_currency', lang('default_currency'), $currency_options, config_item('default_currency'), false, array('class' => 'select_box')); ?>
							</div>
							<?php if ($this->session->userdata('user_type') == '1') { ?>
								<?= btn_modal(
									'admin/settings/new_currency',
									lang('new') . ' ' . lang('currency'),
									lang('new') . ' ' . lang('currency'),
									'sm',
									'plus',
									array('class' => 'inline-flex items-center gap-2 rounded-lg bg-slate-900 px-3 py-2.5 text-xs font-semibold text-white hover:bg-slate-800 dark:hover:bg-slate-700')
								) ?>

								<a href="<?= base_url() ?>admin/settings/all_currency" class="inline-flex items-center rounded-lg border border-border px-3 py-2.5 text-xs font-semibold text-foreground hover:bg-muted" title="<?= lang('view_all_currency'); ?>">
									<i data-lucide="list" class="h-4 w-4"></i>
								</a>

							<?php } ?>
						</div>

							<div class="flex items-start gap-2">
								<div class="flex-1">
									<?= form_lookup_group('default_account', lang('default_account'), config_item('default_account'), $selected_default_account_label, false, array(), '', array('type' => 'account', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('account'))); ?>
								</div>
								<?php if (!empty($acreated)) { ?>
								<?= btn_modal(
									'admin/account/new_account',
									'',
									lang('new') . ' ' . lang('account'),
									'lg',
									'plus',
									array('class' => 'mt-6 inline-flex items-center rounded-lg border border-border px-3 py-2.5 text-xs font-semibold text-foreground hover:bg-muted')
								) ?>
							<?php } ?>
						</div>

						<?= form_select_group('default_payment_method', lang('default') . ' ' . lang('payment_method'), $payment_method_options, config_item('default_payment_method'), false, array('class' => 'select_box')); ?>
						<?= form_select_group('attendance_report', lang('attendance_report'), $attendance_report_options, config_item('attendance_report'), false); ?>
						<?= form_select_group('project_details_view', lang('project_details_view'), $project_view_options, config_item('project_details_view'), false); ?>
						<?= form_select_group('task_details_view', lang('task_details_view'), $task_view_options, config_item('task_details_view'), false); ?>
						<?= form_select_group('activity_style', lang('activities') . ' ' . lang('view'), $activity_style_options, config_item('activity_style') ?: 'timeline', false); ?>
						<?= form_input_group('activity_pagination_limit', lang('activities') . ' ' . lang('pagination'), config_item('activity_pagination_limit') ?: 20, 'number', false, array('min' => 1, 'max' => 100)); ?>
						<?= form_select_group('currency_position', lang('currency_position'), $currency_position_options, config_item('currency_position'), false); ?>

						<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
							<?= form_select_group('date_format', lang('date_format'), $date_format_options, $date_format, false); ?>
							<?= form_select_group('time_format', lang('time_format'), $time_format_options, config_item('time_format'), false); ?>
						</div>

						<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
							<?= form_select_group('money_format', lang('money_format'), $money_format_options, config_item('money_format'), false, array('class' => 'select_2')); ?>
							<?= form_input_group('decimal_separator', lang('decimal_separator'), $decimal_separator, 'text'); ?>
						</div>

						<?= form_input_group('tables_pagination_limit', lang('tables_pagination_limit'), config_item('tables_pagination_limit')); ?>
						<?= form_input_group('allowed_files', lang('allowed_files'), config_item('allowed_files')); ?>
						<?= form_input_group('max_file_size', lang('max_file_size'), config_item('max_file_size')); ?>

						<?php
						$taxes = $this->db->order_by('tax_rate_percent', 'ASC')->get('tbl_tax_rates')->result();
						$default_tax = config_item('default_tax');
						if (!is_numeric($default_tax)) {
							$default_tax = unserialize($default_tax);
						}
						$default_tax_selected_items = array();
						if (!empty($taxes) && !empty($default_tax) && is_array($default_tax)) {
							foreach ($taxes as $tax) {
								if (in_array($tax->tax_rates_id, $default_tax)) {
									$default_tax_selected_items[] = array(
										'id' => $tax->tax_rates_id,
										'text' => $tax->tax_rate_name . ' (' . $tax->tax_rate_percent . '%)',
									);
								}
							}
						}
						?>
						<?= form_multi_lookup_group('default_tax', lang('default_tax'), $default_tax_selected_items, false, array(), '', array('type' => 'tax_rate', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('tax'))); ?>
					</div>

					<div class="space-y-4">
						<?= form_checkbox('allow_geo_clock_in', lang('allow_geo_clock_in'), config_item('allow_geo_clock_in') == 'TRUE'); ?>

						<div id="postmark_config" class="space-y-4" <?php echo (config_item('allow_geo_clock_in') != 'TRUE') ? 'style="display:none"' : '' ?>>
							<?php
							$location_append = '<button type="button" id="get_location" class="inline-flex h-full items-center justify-center text-foreground transition hover:text-primary"><i data-lucide="map-pin" class="h-4 w-4"></i></button>';
							?>
							<?= form_input_group('office_location', lang('office') . ' ' . lang('location'), set_value('office_location', config_item('office_location')), 'text', false, array('id' => 'searchTextField'), '', $location_append); ?>
							<input type="hidden" name="office_lat" id="lat" value="<?= set_value('lat', config_item('office_lat')); ?>">
							<input type="hidden" name="office_long" id="long" value="<?= set_value('long', config_item('office_long')); ?>">
							<?= form_input_group('allowed_radius', lang('allowed') . ' ' . lang('distance') . ' ' . lang('for') . ' ' . lang('login'), set_value('dist_from_office', config_item('allowed_radius')), 'text', false, array('id' => 'dist_from_office')); ?>
						</div>

						<?= form_input_group('chat_interval_time', lang('chat_interval_time'), config_item('chat_interval_time')); ?>
						<?= form_input_group('google_api_key', lang('google_api_key'), config_item('google_api_key')); ?>
						<?= form_input_group('recaptcha_site_key', lang('recaptcha_site_key'), config_item('recaptcha_site_key')); ?>
						<p class="text-xs text-muted-foreground"><?= lang('recaptcha_help') ?></p>
						<?= form_input_group('recaptcha_secret_key', lang('recaptcha_secret_key'), config_item('recaptcha_secret_key')); ?>

						<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
							<?= form_input_group('auto_close_ticket', lang('auto_close_ticket'), config_item('auto_close_ticket')); ?>
							<p class="text-xs text-muted-foreground md:pt-7"><?= lang('hours') . ' ' . lang('required_cron') ?></p>
						</div>

						<?= form_checkbox('enable_languages', lang('enable_languages'), config_item('enable_languages') == 'TRUE'); ?>
						<?= form_checkbox('allow_sub_tasks', lang('allow_sub_tasks'), config_item('allow_sub_tasks') == 'TRUE'); ?>
						<?= form_checkbox('only_allowed_ip_can_clock', lang('only_allowed_ip_can_clock'), config_item('only_allowed_ip_can_clock') == 'TRUE'); ?>
						<?= form_checkbox('allow_client_registration', lang('allow_client_registration'), config_item('allow_client_registration') == 'TRUE'); ?>
						<?= form_checkbox('allow_apply_job_from_login', lang('allow_apply_job_from_login'), config_item('allow_apply_job_from_login') == 'TRUE'); ?>
						<?= form_checkbox('allow_weekend_excluded_from_leave', lang('allow_weekend_excluded_from_leave'), config_item('allow_weekend_excluded_from_leave') == 'TRUE'); ?>
						<?= form_checkbox('allow_custom_permission', lang('allow_custom_permission'), config_item('allow_custom_permission') == 'TRUE'); ?>

						<input name="client_default_menu[]" value="17" type="hidden">
						<?= form_multi_lookup_group('client_default_menu', lang('client_default_menu_permission'), $client_menu_selected_items, true, array(), '', array('type' => 'client_menu', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('modules'))); ?>

						<?= form_checkbox('allow_client_project', lang('allow_client_project'), config_item('allow_client_project') == 'TRUE'); ?>
					</div>
				</div>
			</div>
		</div>
	</form>
</div>

<?php
$google_api_key = config_item('google_api_key');
?>
<script type="text/javascript"
	src="https://maps.googleapis.com/maps/api/js?key=<?= $google_api_key ?>&libraries=places"></script>

<style>
	.pac-container {
		z-index: 99999 !important;
		margin-top: 0.25rem;
		border: 1px solid #cbd5e1 !important;
		border-radius: 0.5rem;
		background: #ffffff;
		box-shadow: 0 10px 30px rgba(15, 23, 42, 0.2);
	}

	.pac-item {
		padding: 0.5rem 0.75rem;
		border-top: 1px solid #e2e8f0;
		font-size: 0.8125rem;
		color: #334155;
	}

	.pac-item:hover {
		background: #f1f5f9;
	}

	.pac-item-query {
		color: inherit;
	}

	.dark .pac-container {
		border-color: #334155 !important;
		background: #0f172a;
		box-shadow: 0 12px 30px rgba(2, 6, 23, 0.55);
	}

	.dark .pac-item {
		border-top-color: #334155;
		background: #0f172a;
		color: #e2e8f0;
	}

	.dark .pac-item:hover {
		background: #1e293b;
	}
</style>


<script>
	function initialize() {
		var input = document.getElementById('searchTextField');
		var autocomplete = new google.maps.places.Autocomplete(input);
		google.maps.event.addListener(autocomplete, 'place_changed', function() {
			var place = autocomplete.getPlace();
			document.getElementById('lat').value = place.geometry.location.lat();
			document.getElementById('long').value = place.geometry.location.lng();
		});
	}

	google.maps.event.addDomListener(window, 'load', initialize);
</script>

<script>
	$(document).on('change', '[name="allow_geo_clock_in"]', function() {
		if (this.checked) {
			$('#postmark_config').slideDown('fast');
		} else {
			$('#postmark_config').slideUp('fast');
		}
	});

	$("#get_location").on("click", function() {
		$("#searchTextField").val('');
		$("#lat").val('');
		$("#long").val('');
		get_geo_data_2();
	});

	function get_geo_data_2() {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(do_action, handle_errors);
		} else {
			alert(<?= json_encode(lang('geolocation_not_supported')) ?>);
		}
	}

	function do_action(position) {
		var latitude = position.coords.latitude;
		var longitude = position.coords.longitude;
		if (latitude != '' && longitude != '') {
			var currgeocoder = new google.maps.Geocoder();
			var location = new google.maps.LatLng(latitude, longitude);
			currgeocoder.geocode({
				'location': location
			}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					$("#searchTextField").val(results[0].formatted_address);
					$("#lat").val(latitude);
					$("#long").val(longitude);
				} else {
					alert(<?= json_encode(lang('geocode_failed')) ?> + ' ' + status);
				}
			});
		}
	}

	function handle_errors(error) {
		switch (error.code) {
			case error.PERMISSION_DENIED:
				alert(<?= json_encode(lang('location_access_required')) ?>);
				break;

			case error.POSITION_UNAVAILABLE:
				alert("could not detect current position");
				break;

			case error.TIMEOUT:
				alert("retrieving position timedout");
				break;

			default:
				alert("unknown error");
				break;
		}
	}
</script>
