<?php

class report_pl_packets_sign extends c_report
{
	var $title='Лог пакетов ПЛ';
	var $view_by_space_filter=1;
	var $type='';
	var $group_id=0;
	var $doctor_id=0;
	var $status='';
	var $no_view_button=0;
	var $left_join=[];

	function setting($options=[])
	{ ?>
		<div id="panel_filter">
			<form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<? echo _CUR_REPORT_DIR ?>">
				<fieldset>
					<div class="row">
						<?
						$this->filter_section_input_text('id', 'ID пакета:', 2);
						$this->filter_section_input_text('driver_name', 'ФИО водителя:', 2);
						$this->filter_section_select('type', 'Тип пакета:', 2, PL()->arr_packet_type);
						if ($this->filter['type'])
						{
							$this->filter_section_select('status', 'Статус пакета:', 2, PL()->arr_packet_titul_status[$this->filter['type']]);
						}
						$this->filter_section_input_text('data_from', 'От:', 2, ['class'=>'datetimepicker']);
						$this->filter_section_input_text('data_to', 'До:', 2, ['class'=>'datetimepicker']);
						?>
					</div>
				</fieldset>
				<? $this->panel_button_apply(); ?>
			</form>
		</div><br>
		<?
	}

	function create_usl_select_obj($_params, &$options)
	{  //damp_array($this->filter) ;//
		$usl=[];
		$usl[]='true';
		if ($this->filter['type'])
		{
			$usl[]='pk.packet_type='.$this->filter['type'];
		}
		if ($this->filter['type'] and $this->filter['status'])
		{
			$usl[]='pk.status='.$this->filter['status'];
		}
		if ($this->type)
		{
			$usl[]='pk.packet_type in ('.$this->type.')';
		}
		if ($this->filter['status'])
		{
			$usl[]='pk.status in ('.$this->filter['status'].')';
		}
		if ($this->status)
		{
			$usl[]='pk.status in ('.$this->status.')';
		}
		if ($this->filter['data_from'])
		{
			$usl[]='pk.c_data>='.strtotime($this->filter['data_from']);
		}
		if ($this->filter['data_to'])
		{
			$usl[]='pk.c_data<='.strtotime($this->filter['data_to']);
		}
		if ($this->filter['id'])
		{
			$usl[]='pk.pkey='.$this->filter['id'];
		}
		if ($this->filter['driver_name'])
		{
			$rec_personal=PERSONAL()->get_personal(['obj_name'=>$this->filter['driver_name']]);
			//damp_array($rec_personal);
			$usl[]=($rec_personal['pkey']) ? 'dr.driver_id='.$rec_personal['pkey'] : 'false';
			$this->left_join['dr']='left join pl_packet_driver dr on dr.packet_id=pk.pkey';
		}
		if ($this->group_id)
		{
			$usl[]='(mo_now.group_id='.$this->group_id.' or mo.group_id='.$this->group_id.')';
			$this->left_join['dr']='left join pl_packet_driver dr on dr.packet_id=pk.pkey';
			$this->left_join['mo_now']='left join obj_site_mo_session_now mo_now on mo_now.pkey=dr.mo_id';
			$this->left_join['mo']='left join obj_site_mo_session mo on mo.pkey=dr.mo_id';
		}
		if ($this->doctor_id)
		{
			$usl[]='(mo_now.doctor_id='.$this->doctor_id.' or mo.doctor_id='.$this->doctor_id.')';
			$this->left_join['dr']='left join pl_packet_driver dr on dr.packet_id=pk.pkey';
			$this->left_join['mo_now']='left join obj_site_mo_session_now mo_now on mo_now.pkey=dr.mo_id';
			$this->left_join['mo']='left join obj_site_mo_session mo on mo.pkey=dr.mo_id';
		}
		//damp_array($usl);


		$usl_res=implode(' and ', $usl);
		return ($usl_res);
	}

	function panel_info_filter()
	{
		$_str=[];
		$info=[];
		$title='';
		if ($this->filter['type'])
		{
			$info['Тип пакета']='"'.PL()->arr_packet_type[$this->filter['type']].'"';
		}
		if ($this->filter['data_from'])
		{
			$info['дата от']='"'.$this->filter['data_from'].'"';
		}
		if ($this->filter['data_to'])
		{
			$info['дата до']='"'.$this->filter['data_to'].'"';
		}
		if (_sizeof($info))
		{
			foreach ($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>';
		}
		if (_sizeof($_str))
		{
			$title='<p class=center>'.implode(' ', $_str).'</p>';
		}
		return $title;
	}

	function get_cnt_items($usl, $options=[])
	{ //$options['debug']=2 ;
		$cnt=execSQL_value('select count(pk.pkey)
                        from  pl_packets pk
                        '.implode("\n", $this->left_join).'
                        where '.$usl, $options);
		return ($cnt);
	}

	function get_items($usl, $options=[])
	{
		$limit=($options['limit']) ? ' '.$options['limit'] : '';
		$order=($this->filter['order']) ? ' order by '.$this->filter['order'] : ' order by pkey desc';
		// $options['debug']=2 ;
		//echo $usl ;
		$list_rec=execSQL('select pk.*,dr.mo_id,
 	                   pl.driver_id as _driver_id,pl.car_id as _car_id,pl.number as _pl_number,pl.uid as _pl_uid,pl.date as _pl_date
                       from  pl_packets pk
                       left join pl_put_list pl on pl.pkey=pk.pl_id
                       '.implode("\n", $this->left_join).'
                       where '.$usl.$order.$limit, $options);
		//if (_sizeof($list_rec)) foreach($list_rec as $id=>$rec) ESMO()->prepare_public_info_to_mo($list_rec[$id],$options) ;
		return ($list_rec);
	}


	// Современный шаблон с карточками и визуальными индикаторами
	function print_template_HTML($list_recs, $options=[])
	{
		$id=($options['id']) ? 'id='.$options['id'] : '';
		$result_mo=(sizeof($list_recs)) ? PL()->get_mo_to_packets($list_recs) : [];

		// Подсчет статистики
		$total=count($list_recs);
		$signed=0;
		$ready_to_sign=0;
		$with_errors=0;

		foreach ($list_recs as $rec)
		{
			if ($rec['sign_size']>0)
			{
				$signed++;
			}
			if ($rec['status']==2 && !$rec['error'])
			{
				$ready_to_sign++;
			}
			if ($rec['error'])
			{
				$with_errors++;
			}
		}

		$progress=$total>0 ? round(($signed/$total)*100) : 0;
		?>

		<!-- Прогресс-бар -->
		<div class="progress-dashboard" data-total="<?= $total ?>" data-signed="<?= $signed ?>">
			<div class="progress-label">
				<span>Прогресс подписи пакетов</span>
				<span class="progress-percentage"><?= $progress ?>%</span>
			</div>
			<div class="progress-bar">
				<div class="progress-fill" style="width: <?= $progress ?>%"></div>
			</div>
			<div class="progress-text"><?= $signed ?> из <?= $total ?> пакетов подписано</div>

			<!-- Кнопка возврата (показывается после завершения) -->
			<div class="completion-actions" style="display: none;">
				<div class="completion-message">
					<i class="fa fa-check-circle"></i>
					<span>Все пакеты успешно подписаны!</span>
				</div>
				<?if ($_GET['from_smenaout']){?>
				<button class="btn-return-to-smena" onclick="window.location.href='/cab/smenaout/'">
					<i class="fa fa-arrow-left"></i> Вернуться в закрытие смены
				</button><?}?>
			</div>
		</div>

		<!-- Список пакетов карточками -->
		<div class="packets-grid" <?= $id ?>>
			<?php
			if (_sizeof($list_recs))
			{
				foreach ($list_recs as $rec)
				{
					// Подготовка данных
					if (!$rec['_car_number'])
					{
						$rec['_car_number']=$rec['car_number'];
					}
					if (!$rec['_pl_number'])
					{
						$rec['_pl_number']=$rec['pl_number'];
					}
					if (!$rec['_pl_uid'])
					{
						$rec['_pl_uid']=$rec['pl_uid'];
					}
					if (!$rec['_pl_date'])
					{
						$rec['_pl_date']=$rec['pl_date'];
					}

					$mo_info=$result_mo[$rec['pkey']];
					$arr_drivers_fio=execSQL_row('select pkey,driver_fio from pl_packet_driver where packet_id='.$rec['pkey']);

					// Определение статуса карточки
					$card_status='pending';
					if ($rec['sign_size']>0)
					{
						$card_status='signed';
					}
					elseif ($rec['status']==2 && !$rec['error'])
					{
						$card_status='ready';
					}
					elseif ($rec['error'])
					{
						$card_status='error';
					}

					$day_from=date('d.m.Y', $rec['titul_date_from']);
					$day_to=date('d.m.Y', $rec['titul_date_to']);
					$date_range=($day_from!=$day_to) ? "$day_from - $day_to" : $day_from;
					?>

					<div class="packet-card <?= $card_status ?>" data-packet-id="<?= $rec['pkey'] ?>">
						<!-- Заголовок карточки -->
						<div class="packet-header">
							<div class="packet-id">
								<a href="/window/pl/packet/<?= $rec['pkey'] ?>/" class="new_window">
									<i class="fa fa-file-text-o"></i> Пакет #<?= $rec['pkey'] ?>
								</a>
							</div>
							<div class="packet-status-badge <?= $card_status ?>">
								<?php if ($card_status=='signed'): ?>
									<i class="fa fa-check-circle"></i> Подписан
								<?php elseif ($card_status=='ready'): ?>
									<i class="fa fa-clock-o"></i> Готов к подписи
								<?php elseif ($card_status=='error'): ?>
									<i class="fa fa-exclamation-circle"></i> Ошибка
								<?php else: ?>
									<i class="fa fa-hourglass-half"></i> В обработке
								<?php endif; ?>
							</div>
						</div>

						<!-- Основная информация -->
						<div class="packet-body">
							<div class="packet-info-grid">
								<!-- Тип и направление -->
								<div class="info-block">
									<div class="info-label">
										<i class="fa fa-exchange"></i> Тип пакета
									</div>
									<div class="info-value">
										<?= PL()->arr_packet_type[$rec['packet_type']] ?>
										<span class="badge-small"><?= PL()->arr_packet_mode[$rec['packet_mode']] ?></span>
									</div>
								</div>

								<!-- Дата -->
								<div class="info-block">
									<div class="info-label">
										<i class="fa fa-calendar"></i> Дата
									</div>
									<div class="info-value">
										<?= $date_range ?>
									</div>
								</div>

								<!-- Водитель -->
								<div class="info-block">
									<div class="info-label">
										<i class="fa fa-id-card"></i> Водитель
									</div>
									<div class="info-value">
										<?php if ($arr_drivers_fio): ?>
											<?= implode(', ', array_slice($arr_drivers_fio, 0, 2)) ?>
											<?php if (count($arr_drivers_fio)>2): ?>
												<span class="badge-small">+<?= (count($arr_drivers_fio)-2) ?></span>
											<?php endif; ?>
										<?php else: ?>
											<span class="text-muted">—</span>
										<?php endif; ?>
									</div>
								</div>

								<!-- Автомобиль -->
								<div class="info-block">
									<div class="info-label">
										<i class="fa fa-truck"></i> Автомобиль
									</div>
									<div class="info-value">
										<?= $rec['_car_number'] ?: '—' ?>
									</div>
								</div>

								<!-- МО -->
								<div class="info-block">
									<div class="info-label">
										<i class="fa fa-stethoscope"></i> МО
									</div>
									<div class="info-value">
										<?= 'ID '.$rec['mo_id'] ?: '—' ?>
									</div>
								</div>

								<!-- Фельдшер -->
								<div class="info-block">
									<div class="info-label">
										<i class="fa fa-user-md"></i> Фельдшер
									</div>
									<div class="info-value">
										<? $rec_mo=ESMO()->get_mo_by_id($rec['mo_id']) ;
										//damp_array($rec_mo);
										echo $rec_mo['_doctor_name'] ;

										?>
									</div>
								</div>

							</div>

						</div>

					</div>
					<?php
				}
			}
			else
			{
				?>
				<div class="empty-state">
					<i class="fa fa-inbox"></i>
					<h3>Нет пакетов для отображения</h3>
					<p>Пакеты на подпись появятся здесь автоматически</p>
				</div>
				<?php
			}
			?>
		</div>

		<style type="text/css">
        /* Прогресс-бар */
        .progress-dashboard {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 20px 25px;
            margin-bottom: 25px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
        }

        .progress-label {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            color: #495057;
            font-weight: 600;
            font-size: 14px;
        }

        .progress-percentage {
            font-size: 20px;
            font-weight: 700;
            color: #2c5282;
            font-family: 'Courier New', monospace;
        }

        .progress-bar {
            height: 8px;
            background: #e9ecef;
            border-radius: 2px;
            overflow: hidden;
            margin-bottom: 10px;
            border: 1px solid #ced4da;
        }

        .progress-fill {
            height: 100%;
            background: #2c5282;
            transition: width 0.8s cubic-bezier(0.4, 0.0, 0.2, 1);
            position: relative;
        }

		.progress-text {
			text-align: right;
			color: #6c757d;
			font-size: 12px;
			font-weight: 500;
		}

		/* Блок завершения */
		.completion-actions {
			margin-top: 20px;
			padding-top: 20px;
			border-top: 2px solid #e9ecef;
			text-align: center;
		}

		.completion-message {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 10px;
			margin-bottom: 15px;
			font-size: 16px;
			font-weight: 600;
			color: #28a745;
		}

		.completion-message i {
			font-size: 24px;
		}

		.btn-return-to-smena {
			padding: 12px 30px;
			background: #2c5282;
			color: white;
			border: none;
			border-radius: 4px;
			font-size: 14px;
			font-weight: 600;
			cursor: pointer;
			transition: all 0.3s ease;
			display: inline-flex;
			align-items: center;
			gap: 8px;
		}

		.btn-return-to-smena:hover {
			background: #1e3a5f;
			transform: translateY(-1px);
			box-shadow: 0 4px 8px rgba(44, 82, 130, 0.3);
		}

		.btn-return-to-smena i {
			font-size: 16px;
		}

		/* Сетка карточек */
        .packets-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        @media (max-width: 768px) {
            .packets-grid {
                grid-template-columns: 1fr;
            }
        }

        /* Карточка пакета */
        .packet-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            border-left: 4px solid #e0e0e0;
            overflow: hidden;
        }

        .packet-card:hover {
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
            transform: translateY(-2px);
        }

        .packet-card.ready {
            border-left-color: #FFA726;
        }

        .packet-card.signed {
            border-left-color: #66BB6A;
        }

        .packet-card.error {
            border-left-color: #EF5350;
        }

        .packet-card.pending {
            border-left-color: #42A5F5;
        }

        /* Анимация успешной подписи */
        .packet-card.signing-success {
            animation: successPulse 1s ease;
            background: linear-gradient(135deg, #E8F5E9 0%, #ffffff 100%);
        }

        @keyframes successPulse {
            0% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.02);
                box-shadow: 0 0 20px rgba(102, 187, 106, 0.6);
            }
            100% {
                transform: scale(1);
            }
        }

        /* Заголовок карточки */
        .packet-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }

        .packet-id {
            font-weight: 600;
            font-size: 14px;
        }

        .packet-id a {
            color: #495057;
            text-decoration: none;
            transition: color 0.2s;
        }

        .packet-id a:hover {
            color: #667eea;
        }

        .packet-id i {
            margin-right: 5px;
            opacity: 0.7;
        }

        /* Статус бейдж */
        .packet-status-badge {
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

        .packet-status-badge.ready {
            background: #FFF3E0;
            color: #F57C00;
        }

        .packet-status-badge.signed {
            background: #E8F5E9;
            color: #2E7D32;
        }

        .packet-status-badge.error {
            background: #FFEBEE;
            color: #C62828;
        }

        .packet-status-badge.pending {
            background: #E3F2FD;
            color: #1565C0;
        }

        /* Тело карточки */
        .packet-body {
            padding: 12px 15px;
        }

        /* Сетка информации */
        .packet-info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-bottom: 10px;
        }

        .info-block {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .info-block-wide {
            grid-column: 1 / -1;
        }

        .info-label {
            font-size: 10px;
            color: #6c757d;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .info-label i {
            margin-right: 4px;
            opacity: 0.7;
        }

        .info-value {
            font-size: 13px;
            color: #212529;
            font-weight: 500;
        }

        .info-subtext {
            font-size: 10px;
            color: #868e96;
            margin-top: 2px;
        }

        .badge-small {
            display: inline-block;
            padding: 2px 8px;
            background: #e9ecef;
            border-radius: 10px;
            font-size: 11px;
            margin-left: 5px;
        }

        .badge-mo {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
        }

        .badge-mo.success {
            background: #E8F5E9;
            color: #2E7D32;
        }

        .badge-mo.error {
            background: #FFEBEE;
            color: #C62828;
        }

        .text-muted {
            color: #adb5bd;
        }

        /* Блок ошибки */
        .packet-error-block {
            background: #FFF3E0;
            border-left: 3px solid #F57C00;
            padding: 8px 10px;
            border-radius: 6px;
            margin-top: 10px;
            font-size: 12px;
            color: #E65100;
        }

        .packet-error-block i {
            margin-right: 6px;
        }

        .error-details {
            margin-top: 6px;
            font-size: 11px;
            color: #6d4c41;
        }

        /* Файлы */
        .packet-files {
            display: flex;
            gap: 8px;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #e9ecef;
        }

        .file-item {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 10px;
            background: #f8f9fa;
            border-radius: 6px;
            font-size: 11px;
            color: #495057;
        }

        .file-item.signed {
            background: #E8F5E9;
            color: #2E7D32;
        }

        .file-item i:first-child {
            font-size: 14px;
        }

        .file-download {
            margin-left: auto;
            color: inherit;
            opacity: 0.7;
            transition: opacity 0.2s;
        }

        .file-download:hover {
            opacity: 1;
        }

        /* Действия */
        .packet-actions {
            display: flex;
            gap: 6px;
            padding: 10px 15px;
            background: #f8f9fa;
            border-top: 1px solid #e9ecef;
            flex-wrap: wrap;
        }

        .btn-action {
            flex: 1;
            min-width: 110px;
            padding: 7px 12px;
            border: 1px solid #dee2e6;
            background: white;
            color: #495057;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }

        .btn-action:hover {
            background: #f8f9fa;
            border-color: #adb5bd;
            transform: translateY(-1px);
        }

        .btn-action.primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
        }

        .btn-action.primary:hover {
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        /* Пустое состояние */
        .empty-state {
            grid-column: 1 / -1;
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 64px;
            color: #dee2e6;
            margin-bottom: 20px;
        }

        .empty-state h3 {
            font-size: 20px;
            margin-bottom: 10px;
            color: #495057;
        }

        .empty-state p {
            font-size: 14px;
            color: #868e96;
        }
		</style>
		<?php
	}

}

?>
