<?php
/**
 * Booking — single appointment (right-rail detail + cancel/complete).
 */
require_once dirname(__DIR__, 3) . '/config.php';
require_once dirname(__DIR__) . '/BookingAPI.php';

Auth::require();
Auth::requirePerm('booking.view');
BookingAPI::ensureSchema();

$tid = current_tenant_id();
$id  = (int)($_GET['id'] ?? 0);

$row = Database::row(
    "SELECT a.*, s.name AS service_name, s.duration_min, s.price_cents, s.currency,
            p.name AS provider_name, p.email AS provider_email
       FROM booking_appointments a
       JOIN booking_services  s ON s.id = a.service_id
       JOIN booking_providers p ON p.id = a.provider_id
      WHERE a.id = ? AND a.tenant_id = ?",
    [$id, $tid]
);

if (!$row) {
    http_response_code(404);
    $pageTitle = 'Appointment not found';
    require SLATE_ROOT . '/admin/partials/header.php';
    echo '<div class="card"><h1>Appointment not found</h1></div>';
    require SLATE_ROOT . '/admin/partials/footer.php';
    exit;
}

$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && Auth::can('booking.manage_appointments')) {
    if (!csrf_verify()) {
        $flash = ['type' => 'error', 'msg' => 'Security check failed.'];
    } else {
        $action = $_POST['_action'] ?? '';
        $newStatus = null;
        if ($action === 'cancel')   $newStatus = 'cancelled';
        elseif ($action === 'complete')  $newStatus = 'completed';
        elseif ($action === 'no_show')   $newStatus = 'no_show';
        elseif ($action === 'reconfirm') $newStatus = 'confirmed';

        if ($newStatus) {
            Database::update('booking_appointments', ['status' => $newStatus],
                'id = ? AND tenant_id = ?', [$id, $tid]);
            AuditLog::record('booking.status_changed', (string)$id, ['to' => $newStatus]);
            Hook::doAction('booking_status_changed', $id, $newStatus);
            $row['status'] = $newStatus;
            $flash = ['type' => 'success', 'msg' => 'Status updated to ' . $newStatus . '.'];
        }
    }
}

$audit = [
    ['action' => 'Appointment created', 'when' => $row['created_at'], 'muted' => false,
     'detail' => 'ref ' . $row['ref']],
];
if ((int)$row['reminder_24h_sent'] === 1) {
    $audit[] = ['action' => '24-hour reminder sent', 'when' => $row['updated_at'], 'muted' => true];
}
if ((int)$row['reminder_1h_sent'] === 1) {
    $audit[] = ['action' => '1-hour reminder sent',  'when' => $row['updated_at'], 'muted' => true];
}
if ($row['status'] !== 'confirmed') {
    $audit[] = ['action' => 'Marked ' . $row['status'], 'when' => $row['updated_at'], 'muted' => false];
}

$pageTitle  = 'Appointment ' . $row['ref'];
$currentNav = 'booking-appointments';

require SLATE_ROOT . '/admin/partials/header.php';
?>

<?php slate_breadcrumbs([
    ['label' => __('dashboard', 'Dashboard'), 'href' => SLATE_URL . '/admin/'],
    ['label' => __('booking', 'Booking'), 'href' => plugin_url('booking', 'admin/index.php')],
    ['label' => 'Appointments', 'href' => plugin_url('booking', 'admin/appointments.php')],
    ['label' => $row['ref']],
]); ?>

<div class="page-header">
    <div>
        <h1>Appointment <code style="font-family:var(--font-mono);font-size:16px;"><?= e($row['ref']) ?></code></h1>
        <p class="page-header-sub">
            <?= e(date('l, j F Y · H:i', strtotime($row['starts_at']))) ?>
            – <?= e(date('H:i', strtotime($row['ends_at']))) ?>
        </p>
    </div>
    <?php if (Auth::can('booking.manage_appointments')): ?>
        <div class="toolbar">
            <form method="post" style="display:inline;margin:0;">
                <?= csrf_field() ?>
                <?php if ($row['status'] === 'confirmed'): ?>
                    <button name="_action" value="complete" class="btn">Mark completed</button>
                    <button name="_action" value="no_show"  class="btn">No-show</button>
                    <button name="_action" value="cancel"   class="btn btn-danger" onclick="return confirm('Cancel this appointment?')">Cancel</button>
                <?php else: ?>
                    <button name="_action" value="reconfirm" class="btn btn-primary">Reconfirm</button>
                <?php endif; ?>
            </form>
        </div>
    <?php endif; ?>
</div>

<?php if ($flash): ?><div class="alert alert-<?= e($flash['type']) ?>"><?= e($flash['msg']) ?></div><?php endif; ?>

<?php slate_page_layout('with-aside'); ?>
    <div class="page-main">
        <div class="card">
            <div class="card-header"><h2>Details</h2></div>
            <ul class="kv-list">
                <li class="kv-row"><span class="kv-label">Service</span>     <span class="kv-value"><?= e($row['service_name']) ?> (<?= (int)$row['duration_min'] ?> min)</span></li>
                <li class="kv-row"><span class="kv-label">Provider</span>    <span class="kv-value"><?= e($row['provider_name']) ?><?php if ($row['provider_email']): ?> · <a href="mailto:<?= e($row['provider_email']) ?>"><?= e($row['provider_email']) ?></a><?php endif; ?></span></li>
                <li class="kv-row"><span class="kv-label">Customer</span>    <span class="kv-value"><?= e($row['customer_name']) ?> · <a href="mailto:<?= e($row['customer_email']) ?>"><?= e($row['customer_email']) ?></a><?php if ($row['customer_phone']): ?> · <?= e($row['customer_phone']) ?><?php endif; ?></span></li>
                <?php if ((int)$row['price_cents'] > 0): ?>
                    <li class="kv-row"><span class="kv-label">Price</span>   <span class="kv-value kv-mono"><?= e($row['currency']) ?> <?= e(number_format(((int)$row['price_cents'])/100, 2)) ?></span></li>
                <?php endif; ?>
                <?php if (!empty($row['notes'])): ?>
                    <li class="kv-row"><span class="kv-label">Notes</span>   <span class="kv-value"><?= nl2br(e($row['notes'])) ?></span></li>
                <?php endif; ?>
            </ul>
        </div>
    </div>

    <aside class="page-aside">
        <div class="aside-card">
            <div class="aside-card-title">Status</div>
            <ul class="kv-list">
                <li class="kv-row"><span class="kv-label">Current</span><span class="kv-value">
                    <?php
                    $bm = ['confirmed'=>['Confirmed','active'],'cancelled'=>['Cancelled','inactive'],'no_show'=>['No show','warning'],'completed'=>['Completed','accent']][$row['status']] ?? ['?',''];
                    ?>
                    <span class="badge badge-<?= e($bm[1]) ?>"><?= e($bm[0]) ?></span>
                </span></li>
                <li class="kv-row"><span class="kv-label">Reference</span><span class="kv-value kv-mono"><?= e($row['ref']) ?></span></li>
                <li class="kv-row"><span class="kv-label">24h reminder</span><span class="kv-value"><?= (int)$row['reminder_24h_sent'] === 1 ? 'Sent' : '—' ?></span></li>
                <li class="kv-row"><span class="kv-label">1h reminder</span> <span class="kv-value"><?= (int)$row['reminder_1h_sent']  === 1 ? 'Sent' : '—' ?></span></li>
            </ul>
        </div>

        <div class="aside-card">
            <div class="aside-card-title">Audit Trail</div>
            <ol class="audit-trail">
                <?php foreach ($audit as $a): if (empty($a['when'])) continue; ?>
                    <li class="audit-trail-item<?= !empty($a['muted']) ? ' is-muted' : '' ?>">
                        <div class="audit-trail-action"><?= e($a['action']) ?></div>
                        <div class="audit-trail-meta"><?= e(date('j M Y, H:i', strtotime($a['when']))) ?></div>
                        <?php if (!empty($a['detail'])): ?>
                            <div class="audit-trail-detail"><?= e($a['detail']) ?></div>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ol>
        </div>
    </aside>
<?php slate_page_layout_end(); ?>

<?php require SLATE_ROOT . '/admin/partials/footer.php'; ?>
