<?php
function daily_briefing_get_work_name($rec_personal)
{
    return ($rec_personal['working'] and _IL('IL_works')->recs[$rec_personal['working']]['obj_name'])
        ? _IL('IL_works')->recs[$rec_personal['working']]['obj_name']
        : '';
}

function daily_briefing_render_personal_info($rec_personal)
{
    ?>
    <table class="cols3 daily_briefing_personal_card">
        <tr>
            <td class="img">
                <img class="shadow main" src="<?= img_clone($rec_personal,'200') ?>">
            </td>
            <td class="info">
                <div class="name"><?= htmlspecialchars($rec_personal['obj_name']) ?></div>
                <?php if ($rec_personal['propusk']) { ?><div><strong>Пропуск:</strong> <?= htmlspecialchars($rec_personal['propusk']) ?></div><?php } ?>
                <?php if ($rec_personal['dr']) { ?><div><strong>Дата рождения:</strong> <?= htmlspecialchars($rec_personal['dr']) ?></div><?php } ?>
                <?php if ($rec_personal['_org_name']) { ?><div><strong>Организация:</strong> <?= htmlspecialchars($rec_personal['_org_name']) ?></div><?php } ?>
                <?php if ($rec_personal['_otdel_name']) { ?><div><strong>Подразделение:</strong> <?= htmlspecialchars($rec_personal['_otdel_name']) ?></div><?php } ?>
                <?php if (daily_briefing_get_work_name($rec_personal)) { ?><div><strong>Должность:</strong> <?= htmlspecialchars(daily_briefing_get_work_name($rec_personal)) ?></div><?php } ?>
                <?php if (!$rec_personal['enabled']) { ?><div class="red bold" style="margin-top:10px;">Сотрудник уволен</div><?php } ?>
            </td>
        </tr>
    </table>
    <style type="text/css">
        table.daily_briefing_personal_card{width:100%;}
        table.daily_briefing_personal_card td{vertical-align:top;text-align:left;}
        table.daily_briefing_personal_card td.img{width:220px;}
        table.daily_briefing_personal_card td.info .name{font-size:22px;font-weight:bold;margin-bottom:15px;}
    </style>
    <?php
}

function daily_briefing_render_stats_summary($briefing_id)
{
    $stats=DAILY_BRIEFING()->get_stats($briefing_id);
    ?>
    <div class="daily_briefing_stats_cards">
        <div class="item today">
            <div class="title">Сегодня</div>
            <div class="stats_row">
                <div class="metric">
                    <span class="label">Прибыло</span>
                    <strong><?= (int)$stats['today']['arrived'] ?></strong>
                </div>
                <div class="metric">
                    <span class="label">Прошло</span>
                    <strong><?= (int)$stats['today']['completed'] ?></strong>
                </div>
            </div>
        </div>
        <div class="item">
            <div class="title">Вчера</div>
            <div class="stats_row">
                <div class="metric">
                    <span class="label">Прибыло</span>
                    <strong><?= (int)$stats['yesterday']['arrived'] ?></strong>
                </div>
                <div class="metric">
                    <span class="label">Прошло</span>
                    <strong><?= (int)$stats['yesterday']['completed'] ?></strong>
                </div>
            </div>
        </div>
        <div class="item">
            <div class="title">За неделю</div>
            <div class="stats_row">
                <div class="metric">
                    <span class="label">Прибыло</span>
                    <strong><?= (int)$stats['week']['arrived'] ?></strong>
                </div>
                <div class="metric">
                    <span class="label">Прошло</span>
                    <strong><?= (int)$stats['week']['completed'] ?></strong>
                </div>
            </div>
        </div>
    </div>
    <style type="text/css">
        div.daily_briefing_stats_cards{display:flex;gap:18px;flex-wrap:wrap;margin:12px 0 25px 0;}
        div.daily_briefing_stats_cards div.item{min-width:220px;padding:18px 20px;border:1px solid #d9e1e7;border-radius:10px;background:#ffffff;box-shadow:0 2px 8px rgba(38,50,56,0.06);}
        div.daily_briefing_stats_cards div.item.today{background:linear-gradient(135deg,#e3f2fd,#f4f9ff);border-color:#90caf9;}
        div.daily_briefing_stats_cards div.item div.title{font-size:18px;font-weight:bold;margin-bottom:14px;color:#263238;}
        div.daily_briefing_stats_cards div.item div.stats_row{display:flex;gap:18px;flex-wrap:wrap;}
        div.daily_briefing_stats_cards div.item div.metric{min-width:82px;}
        div.daily_briefing_stats_cards div.item div.metric span.label{display:block;font-size:12px;text-transform:uppercase;letter-spacing:0.04em;color:#78909c;margin-bottom:4px;}
        div.daily_briefing_stats_cards div.item div.metric strong{font-size:28px;line-height:1;color:#1565c0;}
        div.daily_briefing_stats_cards div.item.today div.metric strong{color:#0d47a1;}
    </style>
    <?php
}

function daily_briefing_render_instructor_stats_table($briefing_id)
{
    $rows=DAILY_BRIEFING()->get_stats_by_instructors($briefing_id);
    ?>
    <h2 style="margin-top:8px;">По инструкторам</h2>
    <p class="small" style="color:#546e7a;margin:0 0 12px 0;">Число сотрудников: кто зарегистрирован при прибытии (прибыло) и кто завершил инструктаж с подписью (прошло), по каждому аккаунту инструктора.</p>
    <?php
    if (!_sizeof($rows)) {?>
        <p class="small" style="color:#78909c;">Нет данных за выбранные периоды.</p>
        <?php
        return;
    }
    ?>
    <div style="overflow-x:auto;">
        <table class="basic fz_small full auto">
            <thead>
            <tr>
                <th rowspan="2" class="left">Инструктор</th>
                <th colspan="2">Сегодня</th>
                <th colspan="2">Вчера</th>
                <th colspan="2">За неделю</th>
            </tr>
            <tr>
                <th>Прибыло</th>
                <th>Прошло</th>
                <th>Прибыло</th>
                <th>Прошло</th>
                <th>Прибыло</th>
                <th>Прошло</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach($rows as $row) {?>
                <tr>
                    <td class="left"><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= (int)$row['today']['arrived'] ?></td>
                    <td><?= (int)$row['today']['completed'] ?></td>
                    <td><?= (int)$row['yesterday']['arrived'] ?></td>
                    <td><?= (int)$row['yesterday']['completed'] ?></td>
                    <td><?= (int)$row['week']['arrived'] ?></td>
                    <td><?= (int)$row['week']['completed'] ?></td>
                </tr>
            <?php }?>
            </tbody>
        </table>
    </div>
    <style type="text/css">
        table.basic thead th{text-align:center;}
        table.basic thead th.left{text-align:left;vertical-align:middle;}
    </style>
    <?php
}

function daily_briefing_render_stitch_stepper($active_step=1,$step_urls=array())
{
    $tabs=array(
        1=>array('badge_done'=>'ЗАВЕРШЕНО','badge_active'=>'В РАБОТЕ','badge_wait'=>'ОЖИДАНИЕ','sub'=>'Сбор группы','url'=>$step_urls[1]),
        2=>array('badge_done'=>'ЗАВЕРШЕНО','badge_active'=>'В РАБОТЕ','badge_wait'=>'ОЖИДАНИЕ','sub'=>'Текущий сеанс','url'=>$step_urls[2]),
        3=>array('badge_done'=>'ЗАВЕРШЕНО','badge_active'=>'В РАБОТЕ','badge_wait'=>'ОЖИДАНИЕ','sub'=>'Подписи участников','url'=>$step_urls[3]),
    );
    ?>
    <div class="daily_briefing_stitch_stepper">
        <?php foreach($tabs as $step_id=>$tab) {
            $st='wait';
            if ($step_id<$active_step) $st='done';
            elseif ($step_id==$active_step) $st='active';
            $badge=($st==='done')?$tab['badge_done']:(($st==='active')?$tab['badge_active']:$tab['badge_wait']);
            ?>
            <a class="stitch_tab <?= htmlspecialchars($st) ?>" href="<?= htmlspecialchars($tab['url']) ?>">
                <div class="stitch_sub"><?= htmlspecialchars($tab['sub']) ?></div>
                <div class="stitch_badge"><?= htmlspecialchars($badge) ?></div>
            </a>
        <?php } ?>
    </div>
    <?php
}

function daily_briefing_render_stats_strip($briefing_id)
{
    ?>
    <div class="daily_briefing_stats_strip" id="daily_briefing_stats_strip_wrap"><?php daily_briefing_render_stats_strip_inner($briefing_id); ?></div>
    <?php
}

function daily_briefing_render_stats_strip_inner($briefing_id)
{
    $stats=DAILY_BRIEFING()->get_stats($briefing_id);
    ?>
    <div class="strip_item"><span class="lbl">Вчера</span><span class="num"><?= (int)$stats['yesterday']['arrived'] ?></span> / <span class="num"><?= (int)$stats['yesterday']['completed'] ?></span></div>
    <div class="strip_item today"><span class="lbl">Сегодня</span><span class="num"><?= (int)$stats['today']['arrived'] ?></span> / <span class="num"><?= (int)$stats['today']['completed'] ?></span></div>
    <div class="strip_item"><span class="lbl">За неделю</span><span class="num"><?= (int)$stats['week']['arrived'] ?></span> / <span class="num"><?= (int)$stats['week']['completed'] ?></span></div>
    <?php
}

function daily_briefing_render_stage1_registration_card($briefing_id)
{
    ?>
    <div class="daily_briefing_stage_card stitch_stage1">
        <div class="stage_card_head">
            <span class="stage_badge">Этап 1</span>
            <h3 class="stage_title">Регистрация участников</h3>
        </div>
        <p class="stage_hint">На текущий сеанс регистрируются все прибывшие участники группы до начала инструктажа.</p>
        <div id="panel_filter" class="one_row daily_briefing_reg_form">
            <form class="sky-form no_box_shadow">
                <fieldset>
                    <div class="row">
                        <section class="col col-12">
                            <label class="label">Номер пропуска</label>
                            <label class="input">
                                <input autofocus type="text" name="propusk" id="propusk" lang="LAT" case="UPPER" value="" placeholder="Введите или отсканируйте">
                            </label>
                            <input type="hidden" id="daily_briefing_id" value="<?= (int)$briefing_id ?>">
                        </section>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
    <?php
}

function daily_briefing_render_conduct_layout_styles()
{
    ?>
    <style type="text/css">
        div.daily_briefing_stitch_stepper{display:flex;width:100%;gap:0;margin:0 0 20px 0;border-radius:8px;overflow:hidden;border:1px solid #cfd8dc;}
        div.daily_briefing_stitch_stepper a.stitch_tab{display:flex;flex:1;min-height:72px;padding:12px 16px;border-right:1px solid #cfd8dc;background:#eceff1;text-decoration:none;align-items:center;justify-content:center;flex-direction:column;gap:8px;}
        div.daily_briefing_stitch_stepper a.stitch_tab:last-child{border-right:0;}
        div.daily_briefing_stitch_stepper a.stitch_tab .stitch_sub{text-align:center;font-size:14px;font-weight:bold;color:#37474f;line-height:1.2;}
        div.daily_briefing_stitch_stepper a.stitch_tab .stitch_badge{display:inline-block;font-size:10px;font-weight:bold;letter-spacing:0.04em;padding:3px 8px;border-radius:999px;background:#dde3ea;color:#607d8b;}
        div.daily_briefing_stitch_stepper a.stitch_tab.done{background:#e8f5e9;}
        div.daily_briefing_stitch_stepper a.stitch_tab.done .stitch_sub{color:#2e7d32;}
        div.daily_briefing_stitch_stepper a.stitch_tab.done .stitch_badge{background:#cfead1;color:#2e7d32;}
        div.daily_briefing_stitch_stepper a.stitch_tab.active{background:#1976d2;color:#fff;}
        div.daily_briefing_stitch_stepper a.stitch_tab.active .stitch_sub{color:#ffffff;}
        div.daily_briefing_stitch_stepper a.stitch_tab.active .stitch_badge{background:#1565c0;color:#e3f2fd;border:1px solid rgba(255,255,255,0.18);}
        div.daily_briefing_stitch_stepper a.stitch_tab.wait{background:#eceff1;}
        div.daily_briefing_stitch_stepper a.stitch_tab.wait .stitch_badge{background:#dde3ea;color:#78909c;}
        div.daily_briefing_stitch_stepper a.stitch_tab:hover{filter:brightness(0.98);}
        div.daily_briefing_stitch_flex{display:flex;gap:24px;align-items:flex-start;margin-bottom:24px;}
        div.daily_briefing_stitch_main_col{flex:1;min-width:0;}
        div.daily_briefing_stitch_sidebar_col{flex-shrink:0;}
        @media (max-width:1100px){
            div.daily_briefing_stitch_flex{flex-direction:column;}
            div.daily_briefing_stitch_sidebar_col{width:100%;max-width:none;}
            div.daily_briefing_sidebar{max-width:none;}
        }
        div.daily_briefing_stage_card{background:#fff;border:1px solid #cfd8dc;border-radius:8px;padding:16px 18px;margin-bottom:16px;}
        div.daily_briefing_stage_card .stage_card_head{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:4px;}
        div.daily_briefing_stage_card .stage_badge{font-size:11px;font-weight:bold;background:#e3f2fd;color:#1565c0;padding:3px 8px;border-radius:4px;}
        div.daily_briefing_stage_card .stage_title{margin:0;font-size:18px;font-weight:bold;color:#263238;}
        div.daily_briefing_stage_card .stage_timer{margin-left:auto;font-size:20px;font-weight:bold;font-variant-numeric:tabular-nums;color:#1565c0;}
        div.daily_briefing_stage_card .stage_hint{font-size:13px;color:#607d8b;margin:8px 0 12px 0;}
        div.daily_briefing_session_note{margin:0 0 14px 0;padding:10px 14px;background:#eef6fb;border:1px solid #c6d9e7;border-radius:8px;color:#455a64;font-size:13px;}
        div.daily_briefing_stage_card.stitch_stage2 .progress_bar_outer{height:10px;background:#eceff1;border-radius:6px;overflow:hidden;margin:6px 0;}
        div.daily_briefing_stage_card.stitch_stage2 .progress_bar_inner{height:100%;background:linear-gradient(90deg,#1976d2,#42a5f5);border-radius:6px;}
        div.daily_briefing_stage_card.stitch_stage2 .progress_label{font-size:12px;color:#546e7a;}
        div.daily_briefing_stage_card.stitch_stage2 .progress_nums{font-size:13px;margin-top:4px;color:#37474f;}
        div.daily_briefing_stage3_inner{min-height:80px;}
        div.daily_briefing_stats_strip{display:flex;flex-wrap:wrap;gap:10px;margin:12px 0 0 0;font-size:13px;}
        div.daily_briefing_stats_strip .strip_item{background:#f0f4f8;padding:8px 12px;border-radius:6px;border:1px solid #d8dee6;}
        div.daily_briefing_stats_strip .strip_item.today{background:#e3f2fd;border-color:#90caf9;}
        div.daily_briefing_stats_strip .strip_item .lbl{font-weight:bold;margin-right:8px;color:#455a64;}
        div.daily_briefing_stats_strip .strip_item .num{font-weight:bold;color:#1565c0;}
    </style>
    <?php
}

function daily_briefing_render_stage2_progress_inner($briefing_id)
{
    $stats=DAILY_BRIEFING()->get_stats($briefing_id);
    $arrived=(int)$stats['today']['arrived'];
    $completed=(int)$stats['today']['completed'];
    $pct=($arrived>0)?(int)round($completed*100/max(1,$arrived)):0;
    ?>
    <div class="progress_label">Прогресс за сегодня (подписано / прибыло)</div>
    <div class="progress_bar_outer"><div class="progress_bar_inner" style="width:<?= (int)$pct ?>%;"></div></div>
    <div class="progress_nums"><?= (int)$completed ?> / <?= (int)$arrived ?> завершено</div>
    <?php
}

function daily_briefing_render_stage2_conduct_card($briefing_id)
{
    ?>
    <div class="daily_briefing_stage_card stitch_stage2" data-briefing-id="<?= (int)$briefing_id ?>">
        <div class="stage_card_head">
            <span class="stage_badge">Этап 2</span>
            <h3 class="stage_title">Проведение инструктажа</h3>
            <span class="stage_timer" id="daily_briefing_timer_display">00:00</span>
        </div>
        <p class="stage_hint">После завершения сбора группы проводится общий инструктаж для всех зарегистрированных на текущий сеанс участников.</p>
        <div class="stage_row">
            <button type="button" class="button v2" id="daily_briefing_timer_btn">Начать инструктаж</button>
        </div>
        <div class="stage_progress" id="daily_briefing_stage2_progress_wrap">
            <?php daily_briefing_render_stage2_progress_inner($briefing_id); ?>
        </div>
        <label class="label" style="margin-top:12px;">Заметки инструктора</label>
        <label class="textarea" style="margin-top:4px;">
            <textarea rows="3" id="daily_briefing_instructor_notes" placeholder="Кратко: темы, замечания…"></textarea>
        </label>
    </div>
    <script type="text/javascript">
    (function(){
        var bid=<?= (int)$briefing_id ?>;
        var key='daily_briefing_notes_'+bid;
        var $ta=$j('#daily_briefing_instructor_notes');
        if ($ta.length && localStorage.getItem(key)) $ta.val(localStorage.getItem(key));
        $ta.on('input',function(){ try{localStorage.setItem(key,$j(this).val());}catch(e){} });
        var sec=0,timer=null;
        var $disp=$j('#daily_briefing_timer_display');
        var $btn=$j('#daily_briefing_timer_btn');
        function fmt(){ var m=Math.floor(sec/60),s=sec%60; return (m<10?'0':'')+m+':'+(s<10?'0':'')+s; }
        $btn.on('click',function(){
            if (timer){ clearInterval(timer); timer=null; $btn.text('Начать инструктаж'); return; }
            sec=0; $disp.text(fmt());
            timer=setInterval(function(){ sec++; $disp.text(fmt()); },1000);
            $btn.text('Пауза / стоп');
        });
    })();
    </script>
    <?php
}

function daily_briefing_render_stage3_sign_card($briefing_id)
{
    ?>
    <div class="daily_briefing_stage_card stitch_stage3">
        <div class="stage_card_head">
            <span class="stage_badge">Этап 3</span>
            <h3 class="stage_title">Подписи участников</h3>
        </div>
        <p class="stage_hint">После завершения общего инструктажа откройте участника по пропуску и получите подпись.</p>
        <div id="panel_filter" class="one_row daily_briefing_reg_form">
            <form class="sky-form no_box_shadow">
                <fieldset>
                    <div class="row">
                        <section class="col col-12">
                            <label class="label">Номер пропуска участника</label>
                            <label class="input">
                                <input autofocus type="text" name="propusk" id="propusk" lang="LAT" case="UPPER" value="" placeholder="Введите или отсканируйте">
                            </label>
                            <input type="hidden" id="daily_briefing_id" value="<?= (int)$briefing_id ?>">
                        </section>
                    </div>
                </fieldset>
            </form>
        </div>
        <div id="daily_briefing_current_pass" class="daily_briefing_stage3_inner"><div class="alert">Выберите участника для подписи</div></div>
    </div>
    <?php
}

function daily_briefing_render_sidebar_registered_list($briefing_id)
{
    $opts=array(
        'briefing_id'=>$briefing_id,
        'status'=>1,
        'date_from'=>date('d.m.Y'),
        'date_to'=>date('d.m.Y'),
        'time_field'=>'arrive_time',
        'order'=>'arrive_time asc'
    );
    if ((int)MEMBER()->rol===9) $opts['account_arrive_id']=(int)MEMBER()->id;
    $recs=DAILY_BRIEFING()->get_passes($opts);
    ?>
    <div class="sb_card sb_registered_list">
        <div class="sb_title">Зарегистрированы на инструктаж</div>
        <?php if (_sizeof($recs)) {
            foreach($recs as $rec) {
                $rec_personal=PERSONAL()->get_personal_by_id($rec['personal_id'],array('no_public_info'=>1));
                ?>
                <div class="sb_person_row">
                    <div class="sb_person_name"><?= htmlspecialchars($rec_personal['obj_name']) ?></div>
                    <div class="sb_person_meta">
                        <?php if ($rec['arrive_time']) { ?><span><?= date('H:i',$rec['arrive_time']) ?></span><?php } ?>
                        <?php if ($rec['propusk']) { ?><span>Пропуск: <?= htmlspecialchars($rec['propusk']) ?></span><?php } ?>
                    </div>
                </div>
            <?php }
        } else { ?>
            <div class="sb_empty">Нет участников, ожидающих подписи.</div>
        <?php } ?>
    </div>
    <?php
}

function daily_briefing_render_conduct_sidebar($briefing_id,$rec_pass=array())
{
    $stats=DAILY_BRIEFING()->get_stats($briefing_id);
    $wait=DAILY_BRIEFING()->get_today_waiting_sign_count($briefing_id);
    $arrived=(int)$stats['today']['arrived'];
    $completed=(int)$stats['today']['completed'];
    ?>
    <div class="daily_briefing_sidebar">
        <div class="sb_card">
            <div class="sb_title">Сводка инструктажа</div>
            <div class="sb_row"><span>Всего прибыло сегодня</span><strong><?= (int)$arrived ?></strong></div>
            <div class="sb_row"><span>Подписано (завершено)</span><strong><?= (int)$completed ?></strong></div>
            <div class="sb_row"><span>Ожидают подписи</span><strong><?= (int)$wait ?></strong></div>
            <?php if ($rec_pass['pkey'] && (int)$rec_pass['status']===1 && $wait>0) { ?>
                <div class="sb_note warn">Пока не все участники завершили инструктаж — проверьте список в журнале.</div>
            <?php } ?>
        </div>
        <?php daily_briefing_render_sidebar_registered_list($briefing_id); ?>
    </div>
    <style type="text/css">
        div.daily_briefing_sidebar{min-width:280px;max-width:340px;}
        div.daily_briefing_sidebar div.sb_card{background:#fff;border:1px solid #cfd8dc;border-radius:8px;padding:16px 18px;margin-bottom:14px;}
        div.daily_briefing_sidebar div.sb_title{font-weight:bold;font-size:16px;margin-bottom:12px;color:#263238;}
        div.daily_briefing_sidebar div.sb_row{display:flex;justify-content:space-between;gap:6px;margin-bottom:8px;font-size:14px;}
        div.daily_briefing_sidebar div.sb_row.small{font-size:12px;color:#546e7a;}
        div.daily_briefing_sidebar div.sb_note{font-size:12px;margin-top:10px;padding:8px;border-radius:6px;background:#eef3f7;color:#546e7a;}
        div.daily_briefing_sidebar div.sb_note.warn{background:#fff3e0;color:#bf360c;}
        div.daily_briefing_sidebar div.sb_registered_list{padding-top:14px;}
        div.daily_briefing_sidebar div.sb_person_row{padding:6px 0;border-top:1px solid #eef2f5;}
        div.daily_briefing_sidebar div.sb_person_row:first-of-type{border-top:0;padding-top:0;}
        div.daily_briefing_sidebar div.sb_person_name{font-size:12px;font-weight:bold;line-height:1.35;color:#37474f;}
        div.daily_briefing_sidebar div.sb_person_meta{font-size:11px;line-height:1.4;color:#78909c;display:flex;gap:10px;flex-wrap:wrap;margin-top:2px;}
        div.daily_briefing_sidebar div.sb_empty{font-size:12px;color:#90a4ae;}
    </style>
    <?php
}

function daily_briefing_render_current_pass_panel($rec_pass)
{
    if (!$rec_pass['pkey']) {
        ?><div class="alert">Отсканируйте или введите пропуск водителя</div><?php
        return;
    }

    $rec_personal=PERSONAL()->get_personal_by_id($rec_pass['personal_id'],array('no_public_info'=>1));
    ?>
    <div class="daily_briefing_current_pass_wrap">
        <div class="daily_briefing_current_pass_status">
            <strong>Статус:</strong> <?= htmlspecialchars($rec_pass['_status_name']) ?>
            <?php if ($rec_pass['arrive_time']) { ?><br><strong>Время прибытия:</strong> <?= date('d.m.Y H:i',$rec_pass['arrive_time']) ?><?php } ?>
            <?php if ($rec_pass['sign_time']) { ?><br><strong>Время завершения:</strong> <?= date('d.m.Y H:i',$rec_pass['sign_time']) ?><?php } ?>
        </div>
        <?php daily_briefing_render_personal_info($rec_personal); ?>
        <?php if ($rec_pass['status']==1) { ?>
            <div class="daily_briefing_sign_block" id="daily_briefing_stage3_anchor">
                <div class="daily_briefing_sign_head">
                    <h2>Этап 3 · Подпись участника группы</h2>
                    <button type="button" id="clear_daily_briefing_sign_<?= $rec_pass['pkey'] ?>" class="daily_briefing_btn_clear_sig" title="Очистить подпись">
                        <i class="fa fa-eraser"></i> Очистить
                    </button>
                </div>
                <link rel="stylesheet" href="/<?= _CLASS_ ?>/ext/interface/signature-pad-master/assets/jquery.signaturepad.css">
                <script src="/<?= _CLASS_ ?>/ext/interface/signature-pad-master/jquery.signaturepad.js"></script>
                <script src="/<?= _CLASS_ ?>/ext/interface/signature-pad-master/assets/json2.min.js"></script>
                <form id="daily_briefing_sign_form_<?= $rec_pass['pkey'] ?>" method="POST" action=""><canvas class="pad"></canvas></form>
                <div class="buttons sky-form no_box_shadow">
                    <button type="button" id="apply_daily_briefing_sign_<?= $rec_pass['pkey'] ?>" class="button v2">Инструктаж проведен</button>
                </div>
                <div id="daily_briefing_sign_alert_<?= $rec_pass['pkey'] ?>" class="alert" style="display:none;"></div>
            </div>
            <style type="text/css">
                div.daily_briefing_current_pass_status{margin-bottom:20px;font-size:18px;}
                div.daily_briefing_sign_block div.daily_briefing_sign_head{display:grid;grid-template-columns:1fr auto;align-items:center;gap:12px;margin-bottom:10px;}
                div.daily_briefing_sign_block div.daily_briefing_sign_head h2{margin:0;font-size:18px;line-height:1.3;min-width:0;}
                div.daily_briefing_sign_block div.daily_briefing_sign_head .daily_briefing_btn_clear_sig{justify-self:end;}
                button.daily_briefing_btn_clear_sig{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;font-size:12px;line-height:1.2;border:1px solid #b0bec5;border-radius:6px;background:#eceff1;color:#455a64;cursor:pointer;}
                button.daily_briefing_btn_clear_sig:hover{background:#dfe4ea;border-color:#90a4ae;}
                button.daily_briefing_btn_clear_sig i{font-size:13px;}
                div.daily_briefing_sign_block canvas{outline:1px solid #aaaaaa;background:#ffffff;width:100%;max-width:800px;height:200px;}
                div.daily_briefing_sign_block div.buttons{margin-top:15px;display:flex;gap:12px;flex-wrap:wrap;justify-content:flex-end;}
                div.daily_briefing_sign_block div.buttons button{margin-right:0;max-width:100%;}
            </style>
            <script type="text/javascript">
                $j(document).ready(function()
                {
                    var formId = 'form#daily_briefing_sign_form_<?= $rec_pass['pkey'] ?>';
                    var api = null;
                    var $canvas = $j(formId + ' canvas');
                    var resizeFn = function() {
                        var w=$j(formId).closest('.daily_briefing_sign_block').width()||800;
                        w=Math.min(800,Math.max(320,w));
                        $canvas.attr({height:200,width:w});
                    };

                    resizeFn();
                    api = $j(formId).signaturePad({
                        drawOnly: true,
                        defaultAction: 'drawIt',
                        validateFields: false,
                        lineWidth: 0,
                        output: null,
                        sigNav: null,
                        name: null,
                        typed: null,
                        typeIt: null,
                        drawIt: null,
                        typeItDesc: null,
                        drawItDesc: null
                    });

                    $j('body').off('click.dailyBriefingApply<?= $rec_pass['pkey'] ?>', '#apply_daily_briefing_sign_<?= $rec_pass['pkey'] ?>');
                    $j('body').on('click.dailyBriefingApply<?= $rec_pass['pkey'] ?>', '#apply_daily_briefing_sign_<?= $rec_pass['pkey'] ?>', function()
                    {
                        var points = api.getSignature();
                        var image = api.getSignatureImage();
                        if (!image || image.length < 100) {
                            $j('#daily_briefing_sign_alert_<?= $rec_pass['pkey'] ?>').html('Подпись некорректна').show();
                            return false;
                        }
                        send_ajax_request({
                            cmd:'daily_briefing/sign_pass',
                            pass_id:<?= (int)$rec_pass['pkey'] ?>,
                            image:image,
                            sign_data:JSON.stringify(points)
                        });
                        return false;
                    });

                    $j('body').off('click.dailyBriefingClear<?= $rec_pass['pkey'] ?>', '#clear_daily_briefing_sign_<?= $rec_pass['pkey'] ?>');
                    $j('body').on('click.dailyBriefingClear<?= $rec_pass['pkey'] ?>', '#clear_daily_briefing_sign_<?= $rec_pass['pkey'] ?>', function()
                    {
                        api.clearCanvas();
                        $j('#daily_briefing_sign_alert_<?= $rec_pass['pkey'] ?>').hide().html('');
                        return false;
                    });
                });
            </script>
        <?php } else { ?>
            <div class="alert green">
                Инструктаж по сотруднику завершен.
                <?php if ($rec_pass['sign_fname']) { ?><br><img src="<?= $rec_pass['__sign_src'] ?>?r=<?= rand(1,10000) ?>" width="250"><?php } ?>
            </div>
        <?php } ?>
    </div>
    <?php
}

function daily_briefing_render_recent_journal($briefing_id,$options=array())
{
    $limit=($options['limit'])?(int)$options['limit']:10;
    $gopts=array('briefing_id'=>$briefing_id,'limit'=>$limit);
    if ((int)MEMBER()->rol===9) $gopts['for_instructor_journal']=1;
    $recs=DAILY_BRIEFING()->get_passes($gopts);
    ?>
    <table class="basic fz_small full auto">
        <tr>
            <th>Время прибытия</th>
            <th>Сотрудник</th>
            <th>Организация</th>
            <th>Должность</th>
            <th>Статус</th>
            <th>Подпись</th>
        </tr>
        <?php if (_sizeof($recs)) {
            foreach($recs as $rec) {
                $rec_personal=PERSONAL()->get_personal_by_id($rec['personal_id'],array('no_public_info'=>1));
                ?><tr>
                    <td><?= ($rec['arrive_time'])?date('d.m.Y H:i',$rec['arrive_time']):'' ?></td>
                    <td class="left"><?= htmlspecialchars($rec_personal['obj_name']) ?></td>
                    <td class="left"><?= htmlspecialchars($rec_personal['_org_name']) ?></td>
                    <td class="left"><?= htmlspecialchars(daily_briefing_get_work_name($rec_personal)) ?></td>
                    <td>
                        <?php if ($rec['status']==2) { ?>
                            <span class="daily_briefing_chip green">подписано</span>
                        <?php } else { ?>
                            <span class="daily_briefing_chip blue">зарегистрирован</span>
                        <?php } ?>
                    </td>
                    <td><?php if ($rec['sign_fname']) { ?><img src="<?= $rec['__sign_src'] ?>?r=<?= rand(1,10000) ?>" width="120"><?php } ?></td>
                </tr><?php
            }
        } else { ?>
            <tr><td colspan="6" class="center">Записей пока нет</td></tr>
        <?php } ?>
    </table>
    <style type="text/css">
        span.daily_briefing_chip{display:inline-block;padding:2px 8px;border-radius:10px;font-size:12px;font-weight:bold;}
        span.daily_briefing_chip.blue{background:#e6f2fb;color:#1f6ea6;}
        span.daily_briefing_chip.green{background:#e8f6e8;color:#2f7f2f;}
    </style>
    <?php
}
