<?php
use yii\helpers\Html;
use yii\helpers\Url;

$this->title = 'Записи клиентов';
$this->params['breadcrumbs'][] = ['label' => 'Панель мастера', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

    <div class="master-appointments">
        <h1><?= Html::encode($this->title) ?></h1>

        <!-- Блок для уведомлений -->
        <div id="appointment-message" style="display: none; margin-bottom: 15px;"></div>

        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Мои записи</h3>
            </div>
            <div class="panel-body">

                <?php if (empty($appointments)): ?>
                    <p class="text-muted">У вас пока нет записей.</p>
                <?php else: ?>
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th>Дата и время</th>
                            <th>Клиент</th>
                            <th>Услуга</th>
                            <th>Статус</th>
                            <th>Оплата</th>
                            <th>Действия</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($appointments as $appointment): ?>
                            <tr id="appointment-<?= $appointment->id ?>">
                                <td>
                                    <?= Yii::$app->formatter->asDatetime($appointment->start_time, 'php:d.m.Y H:i') ?>
                                    <br>
                                    <small class="text-muted">
                                        <?= Yii::$app->formatter->asDuration(strtotime($appointment->end_time) - strtotime($appointment->start_time)) ?>
                                    </small>
                                </td>
                                <td>
                                    <?= Html::encode($appointment->client->surname . ' ' . $appointment->client->name) ?>
                                    <br>
                                    <small><?= Html::encode($appointment->client->phone_number) ?></small>
                                </td>
                                <td>
                                    <?= Html::encode($appointment->service->name) ?>
                                </td>
                                <td class="status-cell">
                                    <?php if ($appointment->status == 0): ?>
                                        <span class="label label-warning">Новая</span>
                                    <?php elseif ($appointment->status == 1): ?>
                                        <span class="label label-success">Подтверждена</span>
                                    <?php elseif ($appointment->status == 2): ?>
                                        <span class="label label-danger">Отменена</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php
                                    $methods = ['cash' => 'Наличные', 'card' => 'Карта', 'online' => 'Онлайн'];
                                    echo $methods[$appointment->payment_method] ?? $appointment->payment_method;
                                    ?>
                                    <?php if ($appointment->additional_info): ?>
                                        <br>
                                        <small><?= Html::encode($appointment->additional_info) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <select class="form-control status-select" data-appointment-id="<?= $appointment->id ?>" style="width: 130px;">
                                        <option value="0" <?= $appointment->status == 0 ? 'selected' : '' ?>>Новая</option>
                                        <option value="1" <?= $appointment->status == 1 ? 'selected' : '' ?>>Подтвердить</option>
                                        <option value="2" <?= $appointment->status == 2 ? 'selected' : '' ?>>Отменить</option>
                                    </select>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>

            </div>
        </div>
    </div>

<?php
$changeStatusUrl = Url::to(['master/change-status']);
$script = <<< JS
    // Смена статуса заявки
    $('.status-select').on('change', function() {
        var select = $(this);
        var appointmentId = select.data('appointment-id');
        var status = select.val();
        var messageDiv = $('#appointment-message');
        var oldValue = select.data('old-value') || select.find('option[selected]').val();
        
        messageDiv.hide().removeClass('alert-success alert-danger');
        
        $.ajax({
            url: '$changeStatusUrl',
            type: 'POST',
            data: {
                id: appointmentId,
                status: status
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Обновляем отображение статуса
                    var statusCell = $('#appointment-' + appointmentId).find('.status-cell');
                    var statusText = '';
                    var statusClass = '';
                    
                    if (status == 0) {
                        statusText = 'Новая';
                        statusClass = 'label-warning';
                    } else if (status == 1) {
                        statusText = 'Подтверждена';
                        statusClass = 'label-success';
                    } else if (status == 2) {
                        statusText = 'Отменена';
                        statusClass = 'label-danger';
                    }
                    
                    statusCell.html('<span class="label ' + statusClass + '">' + statusText + '</span>');
                    
                    // Сохраняем новое значение как старое
                    select.data('old-value', status);
                    
                    // Показываем сообщение
                    messageDiv.addClass('alert alert-success').html('<i class="glyphicon glyphicon-ok"></i> Статус обновлен').fadeIn();
                    setTimeout(function() {
                        messageDiv.fadeOut();
                    }, 2000);
                } else {
                    // Возвращаем старое значение
                    select.val(oldValue);
                    messageDiv.addClass('alert alert-danger').html('<i class="glyphicon glyphicon-exclamation-sign"></i> ' + (response.message || 'Ошибка')).fadeIn();
                }
            },
            error: function() {
                // Возвращаем старое значение
                select.val(oldValue);
                messageDiv.addClass('alert alert-danger').html('<i class="glyphicon glyphicon-exclamation-sign"></i> Ошибка соединения').fadeIn();
            }
        });
    });
    
    // Сохраняем начальное значение
    $('.status-select').each(function() {
        $(this).data('old-value', $(this).val());
    });
JS;

$this->registerJs($script);
?>