<?php
/**
 * Slate — customer dashboard.
 *
 * Profile card on top, plugin-contributed widgets below. Plugins
 * inject HTML cards via the `customer_dashboard_widgets` filter
 * (mirrors `admin_dashboard_widgets`).
 */
require_once dirname(__DIR__) . '/config.php';

Auth::requireCustomer();

$cust = Auth::customer();
$row  = Database::row(
    "SELECT * FROM customers WHERE id = ? AND tenant_id = ?",
    [(int)$cust['id'], current_tenant_id()]
);

$flash = null;

// ── Profile-update POST ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['_action'] ?? '') === 'update_profile') {
    if (!csrf_verify()) {
        $flash = ['type' => 'error', 'msg' => 'Security check failed.'];
    } else {
        $name  = trim((string)($_POST['name']  ?? ''));
        $phone = trim((string)($_POST['phone'] ?? ''));
        Database::update('customers', [
            'name'  => $name  !== '' ? $name  : null,
            'phone' => $phone !== '' ? $phone : null,
        ], 'id = ?', [(int)$cust['id']]);

        // Refresh session payload
        $_SESSION['slate_customer']['name'] = $name;

        AuditLog::record('customer.profile_updated', (string)$cust['id']);
        $flash = ['type' => 'success', 'msg' => 'Profile updated.'];
        $row['name']  = $name;
        $row['phone'] = $phone;
    }
}

// Plugin widgets
$widgets = Hook::applyFilters('customer_dashboard_widgets', []);
if (!is_array($widgets)) $widgets = [];

$pageTitle           = 'Your account';
$customerPageVariant = 'dashboard';
require __DIR__ . '/partials/header.php';
?>

<div class="page-header">
    <div>
        <h1>Hi<?= !empty($row['name']) ? ', ' . e($row['name']) : '' ?></h1>
        <p class="page-header-sub">Manage your profile and see what's going on with your account.</p>
    </div>
</div>

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

<?php if (empty($row['email_verified'])): ?>
    <div class="alert alert-warning" role="status">
        Your email isn't verified yet. Check your inbox for the verification link
        we sent when you registered.
    </div>
<?php endif; ?>

<?php slate_page_layout('with-aside'); ?>

    <div class="page-main">

        <div class="card">
            <div class="card-header"><h2>Your profile</h2></div>
            <form method="post" autocomplete="on">
                <?= csrf_field() ?>
                <input type="hidden" name="_action" value="update_profile">

                <div class="field-row field-row-2">
                    <div class="field">
                        <label class="field-label" for="name">Name</label>
                        <input type="text" id="name" name="name" maxlength="120"
                               value="<?= e($row['name'] ?? '') ?>">
                    </div>
                    <div class="field">
                        <label class="field-label" for="phone">Phone</label>
                        <input type="tel" id="phone" name="phone" maxlength="40"
                               value="<?= e($row['phone'] ?? '') ?>">
                    </div>
                </div>

                <div class="field">
                    <label class="field-label">Email</label>
                    <input type="email" value="<?= e($row['email']) ?>" disabled>
                    <div class="field-hint">Email changes aren't supported yet — contact support.</div>
                </div>

                <button type="submit" class="btn btn-primary">Save profile</button>
            </form>
        </div>

        <?php if (!empty($widgets)): ?>
            <h2 class="mt-6 mb-3">Your activity</h2>
            <?php foreach ($widgets as $widget): ?>
                <?= $widget ?>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="card">
                <div class="empty">
                    <div class="empty-title">No activity yet</div>
                    <div class="text-sm">When you book a service, place an order, or submit a form,
                        it'll show up here.</div>
                </div>
            </div>
        <?php endif; ?>

    </div>

    <aside class="page-aside">
        <div class="aside-card">
            <div class="aside-card-title">Account details</div>
            <ul class="kv-list">
                <li class="kv-row">
                    <span class="kv-label">Email</span>
                    <span class="kv-value"><?= e($row['email']) ?></span>
                </li>
                <li class="kv-row">
                    <span class="kv-label">Status</span>
                    <span class="kv-value">
                        <?php if (!empty($row['email_verified'])): ?>
                            <span class="badge badge-active">Verified</span>
                        <?php else: ?>
                            <span class="badge badge-warning">Unverified</span>
                        <?php endif; ?>
                    </span>
                </li>
                <li class="kv-row">
                    <span class="kv-label">Joined</span>
                    <span class="kv-value">
                        <?= e(date('j M Y', strtotime($row['created_at'] ?? 'now'))) ?>
                    </span>
                </li>
                <?php if (!empty($row['last_login_at'])): ?>
                    <li class="kv-row">
                        <span class="kv-label">Last sign in</span>
                        <span class="kv-value">
                            <?= e(date('j M Y, H:i', strtotime($row['last_login_at']))) ?>
                        </span>
                    </li>
                <?php endif; ?>
            </ul>
        </div>

        <div class="aside-card">
            <div class="aside-card-title">Security</div>
            <p class="text-sm text-muted" style="margin:0 0 var(--space-3);">
                Forgot your password or want to change it? Sign out and use the reset flow.
            </p>
            <a href="<?= e(SLATE_URL) ?>/customer/logout.php" class="btn btn-ghost btn-block">Sign out</a>
        </div>
    </aside>

<?php slate_page_layout_end(); ?>

<?php require __DIR__ . '/partials/footer.php'; ?>
