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

$this->title = 'История записей';
$this->params['breadcrumbs'][] = ['label' => 'Мой профиль', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

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


        <div id="history-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>
                    <?= Html::a('Записаться к мастеру', ['/appointment/create'], ['class' => 'btn btn-success']) ?>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>Дата и время</th>
                                <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>#<?= $appointment->id ?></td>
                                    <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->masterInfo->user->surname . ' ' . $appointment->masterInfo->user->name) ?>
                                        <br>
                                        <small><?= Html::encode($appointment->masterInfo->user->phone_number) ?></small>
                                    </td>
                                    <td><?= Html::encode($appointment->service->name) ?></td>
                                    <td><?= $appointment->service->price ?> руб.</td>
                                    <td>
                                        <?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 elseif ($appointment->status == 3): ?>
                                            <span class="label label-default">Завершена</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>
                                        <?= Html::a('Подробнее', ['view-appointment', 'id' => $appointment->id], ['class' => 'btn btn-sm btn-primary']) ?>

                                        <?php if (in_array($appointment->status, [0, 1])): ?>
                                            <button class="btn btn-sm btn-danger cancel-appointment" data-id="<?= $appointment->id ?>">
                                                Отменить
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>

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

<?php
$cancelUrl = Url::to(['profile/cancel-appointment']);
$script = <<< JS
    // Отмена заявки
    $('.cancel-appointment').on('click', function() {
        var id = $(this).data('id');
        var messageDiv = $('#history-message');
        
        if (confirm('Отменить эту запись?')) {
            $.ajax({
                url: '$cancelUrl',
                type: 'POST',
                data: {id: id},
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Обновляем статус в таблице
                        $('#appointment-' + id).find('td:eq(5)').html('<span class="label label-danger">Отменена</span>');
                        $('#appointment-' + id).find('.cancel-appointment').remove();
                        
                        messageDiv.addClass('alert alert-success').html('<i class="glyphicon glyphicon-ok"></i> ' + response.message).fadeIn();
                        setTimeout(function() {
                            messageDiv.fadeOut();
                        }, 3000);
                    } else {
                        messageDiv.addClass('alert alert-danger').html('<i class="glyphicon glyphicon-exclamation-sign"></i> ' + response.message).fadeIn();
                    }
                }
            });
        }
    });
JS;

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