<?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 AS service_duration_min,
            s.currency AS service_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'] ?? '';
        if ($action === 'cancel') {
            BookingAPI::cancelAppointment($id, trim((string)($_POST['reason'] ?? '')));
            $row['status'] = 'cancelled';
            $flash = ['type' => 'success', 'msg' => 'Appointment cancelled (customer notified).'];
        } elseif ($action === 'reschedule') {
            $res = BookingAPI::rescheduleAppointment($id, (string)($_POST['new_start'] ?? ''));
            if (!empty($res['ok'])) {
                $fresh = Database::row("SELECT starts_at, ends_at FROM booking_appointments WHERE id = ?", [$id]);
                if ($fresh) { $row['starts_at'] = $fresh['starts_at']; $row['ends_at'] = $fresh['ends_at']; }
                $flash = ['type' => 'success', 'msg' => 'Appointment rescheduled (customer notified).'];
            } else {
                $flash = ['type' => 'error', 'msg' => $res['error'] ?? 'Reschedule failed.'];
            }
        } elseif ($action === 'refund') {
            $res = BookingAPI::refundAppointment($id);
            if (!empty($res['ok'])) {
                $row['payment_status'] = 'refunded';
                $flash = ['type' => 'success', 'msg' => 'Refund issued.'];
            } else {
                $flash = ['type' => 'error', 'msg' => $res['error'] ?? 'Refund failed.'];
            }
        } else {
            $map = ['complete' => 'completed', 'no_show' => 'no_show', 'reconfirm' => 'confirmed'];
            $newStatus = $map[$action] ?? null;
            if ($newStatus && BookingAPI::changeStatus($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" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
            <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? The customer will be emailed.')">Cancel</button>
                <?php else: ?>
                    <button name="_action" value="reconfirm" class="btn btn-primary">Reconfirm</button>
                <?php endif; ?>
            </form>
            <?php if ($row['status'] === 'confirmed'): ?>
                <form method="post" style="display:flex;gap:6px;align-items:center;margin:0;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="_action" value="reschedule">
                    <input type="datetime-local" name="new_start" value="<?= e(date('Y-m-d\TH:i', strtotime($row['starts_at']))) ?>" required>
                    <button class="btn">Reschedule</button>
                </form>
            <?php endif; ?>
            <?php if (Auth::can('booking.manage_payments') && in_array(($row['payment_status'] ?? 'none'), ['paid','deposit_paid','partially_refunded'], true)): ?>
                <form method="post" style="display:inline;margin:0;" onsubmit="return confirm('Refund this payment via Stripe?')">
                    <?= csrf_field() ?>
                    <input type="hidden" name="_action" value="refund">
                    <button class="btn btn-danger">Refund</button>
                </form>
            <?php endif; ?>
            <?php if ((int)($row['price_cents'] ?? 0) > 0): ?>
                <a href="<?= e(plugin_url('booking', 'admin/invoice.php')) ?>?id=<?= (int)$row['id'] ?>" class="btn" target="_blank">Invoice</a>
            <?php endif; ?>
        </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>
            <?php
            $actualMin = (int) round((strtotime($row['ends_at']) - strtotime($row['starts_at'])) / 60);
            $cur       = $row['service_currency'] ?: 'USD';
            $addons    = json_decode((string)($row['addons_json'] ?? '[]'), true) ?: [];
            $customVals= json_decode((string)($row['custom_json'] ?? '[]'), true) ?: [];
            $payLabels = ['none'=>'—','pending'=>'Awaiting payment','deposit_paid'=>'Deposit paid','paid'=>'Paid','refunded'=>'Refunded','partially_refunded'=>'Partially refunded'];
            ?>
            <ul class="kv-list">
                <li class="kv-row"><span class="kv-label">Service</span>     <span class="kv-value"><?= e($row['service_name']) ?> (<?= $actualMin ?: (int)$row['service_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['party_size'] ?? 1) > 1): ?>
                    <li class="kv-row"><span class="kv-label">People</span>  <span class="kv-value"><?= (int)$row['party_size'] ?></span></li>
                <?php endif; ?>
                <li class="kv-row"><span class="kv-label">Source</span>     <span class="kv-value"><?= e(ucfirst((string)($row['source'] ?? 'online'))) ?></span></li>
                <?php if ($addons): ?>
                    <li class="kv-row"><span class="kv-label">Add-ons</span> <span class="kv-value"><?= e(implode(', ', array_map(fn($a) => $a['name'] ?? '', $addons))) ?></span></li>
                <?php endif; ?>
                <?php if ((int)($row['price_cents'] ?? 0) > 0): ?>
                    <li class="kv-row"><span class="kv-label">Price</span>   <span class="kv-value kv-mono"><?= e($cur) ?> <?= e(number_format(((int)$row['price_cents'] + (int)($row['tax_cents'] ?? 0))/100, 2)) ?><?php if ((int)($row['tax_cents'] ?? 0) > 0): ?> <span class="text-muted">(incl. tax)</span><?php endif; ?></span></li>
                <?php endif; ?>
                <?php if (($row['payment_status'] ?? 'none') !== 'none'): ?>
                    <li class="kv-row"><span class="kv-label">Payment</span> <span class="kv-value"><?= e($payLabels[$row['payment_status']] ?? $row['payment_status']) ?><?php if ((int)($row['deposit_cents'] ?? 0) > 0): ?> · deposit <?= e($cur) ?> <?= e(number_format(((int)$row['deposit_cents'])/100, 2)) ?><?php endif; ?></span></li>
                <?php endif; ?>
                <?php foreach ($customVals as $ck => $cv): if ($cv === '' || $cv === null) continue; ?>
                    <li class="kv-row"><span class="kv-label"><?= e($ck) ?></span> <span class="kv-value"><?= e(is_array($cv) ? implode(', ', $cv) : (string)$cv) ?></span></li>
                <?php endforeach; ?>
                <?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 = ['pending'=>['Pending','warning'],'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'; ?>
