<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<?php
$all_customer_group = $this->db->where('type', 'projects')->order_by('customer_group_id', 'DESC')->get('tbl_customer_group')->result();
$all_client = $this->project_model->get_permission('tbl_client');
$created = can_action('57', 'created');
$edited = can_action('57', 'edited');

$projects_id = !empty($project_info) ? $project_info->project_id : null;
$project_no = '';
if (!empty($project_info->project_no)) {
	$project_no = $project_info->project_no;
} else {
	if (empty(config_item('projects_number_format'))) {
		$project_no .= config_item('projects_prefix');
	}
	$project_no .= $this->project_model->generate_projects_number();
}

$project_permissions = $this->db->get('tbl_project_settings')->result();
$current_permissions = !empty($project_info->project_settings) ? $project_info->project_settings : '{"settings":"on"}';
$get_permissions = json_decode($current_permissions);

$permissionL = !empty($project_info->permission) ? $project_info->permission : null;
$progress_value = !empty($project_info) ? $this->project_model->get_project_progress($project_info->project_id) : 0;
$estimate_hours = '';
if (!empty($project_info->estimate_hours)) {
	$parts = explode(':', $project_info->estimate_hours);
	$estimate_hours = isset($parts[0]) ? $parts[0] : '0';
	if (isset($parts[1])) {
		$estimate_hours .= '.' . $parts[1];
	}
}

$billing_type = !empty($project_info->billing_type) ? $project_info->billing_type : 'fixed_rate';
$status_val = !empty($project_info->project_status) ? $project_info->project_status : 'started';

// Build select options
$categories = array('' => lang('none'));
if (!empty($all_customer_group)) {
	foreach ($all_customer_group as $customer_group) {
		$categories[$customer_group->customer_group_id] = $customer_group->customer_group;
	}
}
$clients = array();
if (!empty($all_client)) {
	foreach ($all_client as $v_client) {
		$clients[$v_client->client_id] = $v_client->name;
	}
}
// inline add new customer modal
$new_client_html = form_select_add_link(
	'client_id',
	base_url('admin/client/new_client'),
	lang('create') . ' ' . lang('client'),
	'md'
);
?>

<?= message_box('success'); ?>
<?= message_box('error'); ?>

<?php if (!empty($created) || !empty($edited)) : ?>
	<div class="rounded-2xl border border-border bg-card shadow-sm">
		<div class="px-6 py-5 flex justify-between items-start border-b border-border">
			<div class="flex items-center">
				<div>
					<h3 class="text-xl font-bold text-foreground"><?= lang('new_project'); ?></h3>
					<p class="text-sm mt-1 text-muted-foreground"><?= lang('fill_form_fields'); ?></p>
				</div>
			</div>
			<div class="flex gap-2">
				<?= btn_back(lang('back')); ?>
				<?= btn_info('admin/projects/import', lang('import') . ' ' . lang('project'), '', 'sm'); ?>

			</div>
		</div>

		<?php echo form_open(base_url('admin/projects/saved_project/' . $projects_id), array('class' => 'p-6 space-y-6', 'enctype' => 'multipart/form-data', 'data-parsley-validate' => '', 'role' => 'form')); ?>
		<div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
			<!-- Main columns -->
			<div class="lg:col-span-2 space-y-4">
				<div class="bg-slate-50 p-4 rounded-xl border border-slate-200 dark:bg-slate-800 dark:border-slate-700">
					<h4 class="text-sm font-semibold text-foreground flex items-center gap-2 font-semibold text-sm text-slate-900 mb-3 border-b border-slate-200 pb-2 dark:text-slate-100 dark:border-slate-700">
						<i data-lucide="info" class="h-5 w-5"></i>
						<?= lang('general'); ?>
					</h4>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
						<!-- Left: primary fields -->
						<div class="lg:col-span-2 space-y-5">
							<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
								<?= form_input_group('project_name', lang('project_name'), !empty($project_info->project_name) ? $project_info->project_name : '', 'text', true, ['placeholder' => 'e.g. Q4 Marketing Campaign']); ?>
								<?= form_input_group('project_no', lang('project_no'), $project_no, 'text', true, ['readonly' => true]); ?>
							</div>

							<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
								<?= form_select_group('client_id', lang('client'), $clients, !empty($project_info->client_id) ? $project_info->client_id : (!empty($client_id) ? $client_id : ''), true, ['data-search' => true], '', $new_client_html); ?>
								<?= form_select_group('project_status', lang('status'), array(
									'started' => lang('started'),
									'in_progress' => lang('in_progress'),
									'on_hold' => lang('on_hold'),
									'cancel' => lang('cancel'),
									'completed' => lang('completed'),
								), $status_val, true, array('multiple' => true, 'data-search' => true)); ?>
							</div>

							<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
								<?= form_datepicker('start_date', lang('start_date'), !empty($project_info->start_date) ? date('Y-m-d', safe_strtotime($project_info->start_date)) : '', true, ['id' => 'start-date', 'data-max' => '#end-date', 'data-auto-close' => 'true']); ?>
								<?= form_datepicker('end_date', lang('deadline'), !empty($project_info->end_date) ? date('Y-m-d', safe_strtotime($project_info->end_date)) : '', true, ['id' => 'end-date', 'data-min' => '#start-date', 'data-auto-close' => 'true']); ?>
							</div>

							<?= form_editor('description', lang('description'), !empty($project_info->description) ? $project_info->description : '', false); ?>

							<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
								<div class="bg-slate-50 p-4 rounded-xl border border-slate-200 dark:bg-slate-800 dark:border-slate-700">
									<h4 class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3"><?= lang('preferences'); ?></h4>
									<label class="flex items-center cursor-pointer mb-3">
										<div class="relative">
											<input type="checkbox" name="enable_notifications" class="sr-only peer" value="1" <?= !empty($project_info->enable_notifications) ? 'checked' : ''; ?>>
											<div class="w-11 h-6 bg-slate-200 dark:bg-slate-600 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
										</div>
										<span class="ml-3 text-sm font-medium text-slate-700 dark:text-slate-300"><?= lang('enable_notifications'); ?></span>
									</label>

									<div class="space-y-3">
										<label class="flex items-center space-x-3 cursor-pointer group select-none">
											<input type="radio" name="visibility" value="public" class="peer sr-only" <?= empty($project_info) || (!empty($project_info->visibility) && $project_info->visibility == 'public') ? 'checked' : ''; ?>>
											<div class="w-5 h-5 flex items-center justify-center border-2 border-slate-300 dark:border-slate-600 rounded-full bg-white dark:bg-slate-800 peer-checked:border-blue-600 transition-all peer-focus:ring-2 peer-focus:ring-blue-500/30">
												<div class="w-2.5 h-2.5 bg-blue-600 rounded-full transform scale-0 peer-checked:scale-100 transition-transform"></div>
											</div>
											<span class="text-sm text-slate-700 dark:text-slate-300 group-hover:text-slate-900 dark:group-hover:text-white transition-colors"><?= lang('public'); ?></span>
										</label>
										<label class="flex items-center space-x-3 cursor-pointer group select-none">
											<input type="radio" name="visibility" value="private" class="peer sr-only" <?= !empty($project_info->visibility) && $project_info->visibility == 'private' ? 'checked' : ''; ?>>
											<div class="w-5 h-5 flex items-center justify-center border-2 border-slate-300 dark:border-slate-600 rounded-full bg-white dark:bg-slate-800 peer-checked:border-blue-600 transition-all peer-focus:ring-2 peer-focus:ring-blue-500/30">
												<div class="w-2.5 h-2.5 bg-blue-600 rounded-full transform scale-0 peer-checked:scale-100 transition-transform"></div>
											</div>
											<span class="text-sm text-slate-700 dark:text-slate-300 group-hover:text-slate-900 dark:group-hover:text-white transition-colors"><?= lang('private'); ?></span>
										</label>
									</div>
								</div>

								<div class="bg-slate-50 p-4 rounded-xl border border-slate-200 dark:bg-slate-800 dark:border-slate-700">
									<h4 class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3"><?= lang('progress'); ?></h4>
									<div class="flex items-center gap-3">
										<input type="range" min="0" max="100" value="<?= $progress_value; ?>" data-range-display="#progress_display_main" id="progress_slider_main" class="w-full focus:outline-none">
										<span id="progress_display_main" class="text-sm font-semibold text-indigo-600"><?= $progress_value; ?>%</span>
									</div>
									<input type="hidden" name="progress" id="progress_hidden_main" value="<?= $progress_value; ?>">
								</div>
							</div>

							<div class="bg-slate-50 p-4 rounded-xl border border-slate-200 dark:bg-slate-800 dark:border-slate-700">
								<h4 class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-4"><?= lang('attachments'); ?></h4>
								<div class="space-y-4">
									<?= form_attachment_group([
										'type' => 'dropzone',
										'dropzone_id' => 'project-attachments-dropzone',
										'list_id' => 'project-upload-list',
									]); ?>
									<?= form_attachment_group(['type' => 'simple']); ?>
									<?= form_attachment_group(['type' => 'photo']); ?>
								</div>
							</div>

							<!-- <div>
					<label class="block text-sm font-semibold text-slate-700 mb-2"><?= lang('attachment'); ?></label>
					<div class="border-2 border-dashed border-slate-300 rounded-lg p-6 flex flex-col items-center justify-center text-center hover:bg-slate-50 transition-colors">
						<i class="ph ph-cloud-arrow-up text-3xl text-slate-400 mb-2"></i>
						<p class="text-sm text-slate-600"><span class="font-semibold text-indigo-600"><?= lang('click_to_upload'); ?></span> <?= lang('or_drag_drop'); ?></p>
						<p class="text-xs text-slate-400 mt-1">SVG, PNG, JPG or GIF (max. 800x400px)</p>
						<input type="file" name="attachments[]" class="opacity-0 absolute inset-0 cursor-pointer">
					</div>
				</div> -->
						</div>

						<!-- Right: side panels -->
						<div class="space-y-5">
							<div class="bg-slate-50 p-4 rounded-xl border border-slate-200 dark:bg-slate-800 dark:border-slate-700">
								<h4 class="font-semibold text-sm text-slate-900 mb-3 border-b border-slate-200 pb-2 dark:text-slate-100 dark:border-slate-700"><?= lang('financials'); ?></h4>
								<div class="space-y-3">
									<?= form_input_group('project_cost', lang('project_cost'), !empty($project_info->project_cost) ? $project_info->project_cost : '', 'number', false, ['step' => '0.01'], 'stacked', '$'); ?>
									<?= form_input_group('hourly_rate', lang('project_hourly_rate'), !empty($project_info->hourly_rate) ? $project_info->hourly_rate : '', 'number', false, ['step' => '0.01'], 'stacked', '$'); ?>
									<?= form_select_group('billing_type', lang('billing_type'), array(
										'fixed_rate' => lang('fixed_rate'),
										'project_hours' => lang('only') . ' ' . lang('project_hours'),
										'tasks_hours' => lang('only') . ' ' . lang('tasks_hours'),
										'tasks_and_project_hours' => lang('tasks_and_project_hours'),
									), $billing_type, true); ?>
									<?= form_input_group('estimate_hours', lang('estimate_hours'), $estimate_hours, 'number', false, ['step' => '0.01'], 'stacked', '', 'hrs'); ?>
								</div>
							</div>

							<div class="bg-slate-50 p-4 rounded-xl border border-slate-200">
								<h4 class="font-semibold text-sm text-slate-900 mb-3 border-b border-slate-200 pb-2"><?= lang('settings'); ?></h4>
								<div class="space-y-3">
									<?= form_select_group('category_id', lang('categories'), $categories, !empty($project_info->category_id) ? $project_info->category_id : '', false); ?>
									<?= form_tags_group(!empty($project_info->tags) ? $project_info->tags : ''); ?>
									<?= form_input_group('project_color', lang('color'), !empty($project_info->project_color) ? $project_info->project_color : '#3b82f6', 'text', false, ['class' => 'tw-colorpicker']); ?>
									<?= form_input_group('demo_url', lang('demo_url'), !empty($project_info->demo_url) ? $project_info->demo_url : '', 'url', false); ?>
								</div>
							</div>

							<div class="bg-slate-50 p-4 rounded-xl border border-slate-200">
								<h4 class="font-semibold text-sm text-slate-900 mb-3 border-b border-slate-200 pb-2"><?= lang('team_members'); ?></h4>
								<?= get_permission(3, 8, $assign_user, $permissionL, lang('assined_to')); ?>
							</div>

							<div class="bg-slate-50 p-4 rounded-xl border border-slate-200">
								<h4 class="font-semibold text-sm text-slate-900 mb-3 border-b border-slate-200 pb-2"><?= lang('project_settings'); ?></h4>
								<div class="space-y-2">
									<?php foreach ($project_permissions as $v_permissions) : ?>
										<label class="flex items-center space-x-3 cursor-pointer group select-none">
											<input type="checkbox" class="peer sr-only" name="<?= $v_permissions->settings_id; ?>" value="<?= $v_permissions->settings; ?>"
												<?php
												if (!empty($project_info->project_settings)) {
													if (in_array($v_permissions->settings, $get_permissions)) {
														echo 'checked';
													}
												} else {
													echo 'checked';
												}
												?>>
											<div class="checkbox-icon w-5 h-5 flex items-center justify-center border-2 border-slate-300 dark:border-slate-600 rounded bg-white dark:bg-slate-800 peer-checked:bg-indigo-600 peer-checked:border-indigo-600 transition-all peer-focus:ring-2 peer-focus:ring-indigo-500/30 text-white"></div>
											<span class="text-sm text-slate-700 dark:text-slate-300 group-hover:text-slate-900 dark:group-hover:text-white transition-colors"><?= lang($v_permissions->settings); ?></span>
										</label>
									<?php endforeach; ?>
								</div>
							</div>

							<?= custom_form_Fields(4, $projects_id); ?>
						</div>
					</div>

					<div class="flex justify-end gap-2 pt-4 border-t border-slate-100 mt-4">
						<button type="button" onclick="goBack()" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 shadow-sm transition-colors hover:bg-slate-50 hover:text-slate-900 focus:outline-none focus:ring-2 focus:ring-slate-500/10 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-white"><?= lang('cancel'); ?></button>
						<button type="submit" class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-indigo-700 transition">
							<?= !empty($project_info) ? lang('updates') : lang('save'); ?>
						</button>
					</div>

					<script>
						(function() {
							function bindProgress(sliderId, displayId, hiddenId) {
								const s = document.getElementById(sliderId);
								const d = document.getElementById(displayId);
								const h = document.getElementById(hiddenId);
								if (!s || !d || !h) return;
								const update = (val) => {
									d.textContent = val + '%';
									h.value = val;
								};
								s.addEventListener('input', (e) => update(e.target.value));
								update(s.value);
							}

							function bindDateRange(startId, endId) {
								const start = document.getElementById(startId);
								const end = document.getElementById(endId);
								if (!start || !end) return;
								const updateEndMin = () => {
									if (end._twDatepicker) {
										end._twDatepicker.setMinDate(start.value || null);
									}
								};
								const updateStartMax = () => {
									if (start._twDatepicker) {
										start._twDatepicker.setMaxDate(end.value || null);
									}
								};
								start.addEventListener('change', updateEndMin);
								end.addEventListener('change', updateStartMax);
								updateEndMin();
								updateStartMax();
							}
							document.addEventListener('DOMContentLoaded', () => {
								bindProgress('progress_slider_main', 'progress_display_main', 'progress_hidden_main');
								bindDateRange('start-date', 'end-date');
							});
						})();
					</script>

					<?php echo form_close(); ?>
				</div>
			</div>
		</div>
	</div>
<?php endif; ?>
