<?php
// /htdocs/pages/vendor/dashboard.php — VENDOR COMMAND CENTER
// 28 quick actions · Onboarding · KPIs · Health strip · Subscription · Backup

if (!defined('APP_START')) {
    http_response_code(403);
    exit('Direct access denied');
}

$vendor = getVendor();
if (!$vendor) {
    if (function_exists('setMessage')) setMessage('Vendor access required', 'error');
    redirect('/?page=dashboard');
    exit;
}

$vendorId = (int)$vendor['id'];
$userId   = (int)($_SESSION['user_id'] ?? 0);
$db       = db();
$baseCurrency = $vendor['currency'] ?? 'USD';

// ============================================
// SAFE HELPERS
// ============================================
if (!function_exists('vdQ')) {
    function vdQ($sql, $p = []) {
        try { return db()->fetchOne($sql, $p); } catch (Throwable $e) { return null; }
    }
}
if (!function_exists('vdQA')) {
    function vdQA($sql, $p = []) {
        try { return db()->fetchAll($sql, $p); } catch (Throwable $e) { return []; }
    }
}
if (!function_exists('vdMoney')) {
    function vdMoney($amount, $currency = 'USD') {
        return $currency . ' ' . number_format((float)$amount, 2);
    }
}
if (!function_exists('vdInitials')) {
    function vdInitials($name) {
        $parts = preg_split('/\s+/', trim((string)$name));
        $out = '';
        foreach (array_slice($parts, 0, 2) as $p) $out .= strtoupper(substr($p, 0, 1));
        return $out ?: 'G';
    }
}

// ============================================
// CORE STATS
// ============================================
$stats = [
    'properties'       => (int)(vdQ("SELECT COUNT(*) AS c FROM properties WHERE vendor_id = ? AND is_active = 1", [$vendorId])['c'] ?? 0),
    'bookings_total'   => (int)(vdQ("SELECT COUNT(*) AS c FROM bookings WHERE vendor_id = ?", [$vendorId])['c'] ?? 0),
    'bookings_month'   => (int)(vdQ("SELECT COUNT(*) AS c FROM bookings WHERE vendor_id = ? AND created_at >= DATE_FORMAT(CURDATE(),'%Y-%m-01')", [$vendorId])['c'] ?? 0),
    'pending'          => (int)(vdQ("SELECT COUNT(*) AS c FROM bookings WHERE vendor_id = ? AND status = 'pending'", [$vendorId])['c'] ?? 0),
    'checked_in'       => (int)(vdQ("SELECT COUNT(*) AS c FROM bookings WHERE vendor_id = ? AND status = 'checked_in'", [$vendorId])['c'] ?? 0),
    'revenue_total'    => (float)(vdQ("SELECT COALESCE(SUM(total_amount),0) AS t FROM bookings WHERE vendor_id = ? AND status IN ('completed','checked_out','confirmed','checked_in')", [$vendorId])['t'] ?? 0),
    'revenue_month'    => (float)(vdQ("SELECT COALESCE(SUM(total_amount),0) AS t FROM bookings WHERE vendor_id = ? AND status IN ('completed','checked_out','confirmed','checked_in') AND created_at >= DATE_FORMAT(CURDATE(),'%Y-%m-01')", [$vendorId])['t'] ?? 0),
    'revenue_today'    => (float)(vdQ("SELECT COALESCE(SUM(total_amount),0) AS t FROM bookings WHERE vendor_id = ? AND DATE(created_at) = CURDATE() AND status != 'cancelled'", [$vendorId])['t'] ?? 0),
    'arrivals_today'   => (int)(vdQ("SELECT COUNT(*) AS c FROM bookings WHERE vendor_id = ? AND check_in = CURDATE() AND status IN ('confirmed','pending')", [$vendorId])['c'] ?? 0),
    'departures_today' => (int)(vdQ("SELECT COUNT(*) AS c FROM bookings WHERE vendor_id = ? AND check_out = CURDATE() AND status = 'checked_in'", [$vendorId])['c'] ?? 0),
    'rooms_total'      => (int)(vdQ("SELECT COUNT(*) AS c FROM room_types WHERE property_id IN (SELECT id FROM properties WHERE vendor_id = ?) AND is_active = 1", [$vendorId])['c'] ?? 0),
    'dirty_rooms'      => 0,
    'avg_rate'         => 0.0,
    'occupancy'        => 0.0,
];

$roomsBookedNow = (int)(vdQ(
    "SELECT COUNT(*) AS c FROM bookings
     WHERE vendor_id = ? AND status IN ('confirmed','checked_in')
     AND check_in <= CURDATE() AND check_out > CURDATE()",
    [$vendorId]
)['c'] ?? 0);

$stats['occupancy'] = $stats['rooms_total'] > 0
    ? round(($roomsBookedNow / $stats['rooms_total']) * 100, 1)
    : 0;

$stats['avg_rate'] = (float)(vdQ(
    "SELECT COALESCE(AVG(total_amount / GREATEST(total_nights, 1)), 0) AS adr
     FROM bookings
     WHERE vendor_id = ? AND status IN ('completed','checked_out','confirmed','checked_in')",
    [$vendorId]
)['adr'] ?? 0);

try {
    $stats['dirty_rooms'] = (int)(vdQ(
        "SELECT COUNT(*) AS c FROM housekeeping_status h
         LEFT JOIN room_types rt ON h.room_type_id = rt.id
         WHERE rt.property_id IN (SELECT id FROM properties WHERE vendor_id = ?)
         AND h.status = 'dirty'",
        [$vendorId]
    )['c'] ?? 0);
} catch (Throwable $e) {}

// ============================================
// EXTENDED KPIs
// ============================================
$extended = [
    'concierge_pending' => 0,
    'concierge_urgent'  => 0,
    'dining_today'      => 0,
    'dining_covers'     => 0,
    'hk_dirty'          => 0,
    'hk_occupied'       => 0,
    'maintenance_open'  => 0,
    'laundry_active'    => 0,
];

try {
    $r = vdQ(
        "SELECT
            COUNT(CASE WHEN status IN ('pending','in_progress') THEN 1 END) AS pending,
            COUNT(CASE WHEN priority IN ('urgent','high') AND status IN ('pending','in_progress') THEN 1 END) AS urgent
         FROM concierge_requests WHERE vendor_id = ?",
        [$vendorId]
    );
    if ($r) {
        $extended['concierge_pending'] = (int)$r['pending'];
        $extended['concierge_urgent']  = (int)$r['urgent'];
    }
} catch (Throwable $e) {}

try {
    $r = vdQ(
        "SELECT
            COUNT(*) AS bookings,
            COALESCE(SUM(party_size), 0) AS covers
         FROM dining_reservations
         WHERE vendor_id = ?
           AND reservation_date = CURDATE()
           AND status NOT IN ('cancelled','no_show')",
        [$vendorId]
    );
    if ($r) {
        $extended['dining_today']  = (int)$r['bookings'];
        $extended['dining_covers'] = (int)$r['covers'];
    }
} catch (Throwable $e) {}

try {
    $r = vdQ(
        "SELECT
            COUNT(CASE WHEN rs.status = 'dirty' THEN 1 END) AS dirty,
            COUNT(CASE WHEN rs.occupied = 1 THEN 1 END) AS occupied
         FROM room_status rs
         WHERE rs.vendor_id = ?",
        [$vendorId]
    );
    if ($r) {
        $extended['hk_dirty']    = (int)$r['dirty'];
        $extended['hk_occupied'] = (int)$r['occupied'];
    }
} catch (Throwable $e) {}

try {
    $r = vdQ(
        "SELECT COUNT(*) AS c FROM maintenance_requests
         WHERE vendor_id = ? AND status NOT IN ('resolved','closed','cancelled')",
        [$vendorId]
    );
    if ($r) $extended['maintenance_open'] = (int)$r['c'];
} catch (Throwable $e) {}

try {
    $r = vdQ(
        "SELECT COUNT(*) AS c FROM laundry_orders
         WHERE vendor_id = ? AND status IN ('pending','in_progress','ready')",
        [$vendorId]
    );
    if ($r) $extended['laundry_active'] = (int)$r['c'];
} catch (Throwable $e) {}

// ============================================
// BACKUP HEALTH
// ============================================
$backupHealth = ['count' => 0, 'newest' => null, 'days_since' => null, 'status' => 'unknown'];
try {
    $r = vdQ(
        "SELECT COUNT(*) AS c, MAX(created_at) AS newest
         FROM vendor_backups WHERE vendor_id = ?",
        [$vendorId]
    );
    if ($r) {
        $backupHealth['count'] = (int)$r['c'];
        $backupHealth['newest'] = $r['newest'];
        if ($r['newest']) {
            $backupHealth['days_since'] = (int)floor((time() - strtotime($r['newest'])) / 86400);
            if ($backupHealth['days_since'] <= 3) $backupHealth['status'] = 'good';
            elseif ($backupHealth['days_since'] <= 7) $backupHealth['status'] = 'warn';
            else $backupHealth['status'] = 'critical';
        } else {
            $backupHealth['status'] = 'critical';
        }
    }
} catch (Throwable $e) {}

// ============================================
// CHANNEL SYNC
// ============================================
$channelStats = ['connected' => 0, 'total' => 5, 'errors' => 0, 'active' => 0];
try {
    $r = vdQ(
        "SELECT
            COUNT(CASE WHEN api_key IS NOT NULL AND api_key != '' THEN 1 END) AS connected,
            COUNT(CASE WHEN is_active = 1 THEN 1 END) AS active,
            COUNT(CASE WHEN sync_status = 'failed' THEN 1 END) AS errors
         FROM channel_configs WHERE vendor_id = ?",
        [$vendorId]
    );
    if ($r) {
        $channelStats['connected'] = (int)$r['connected'];
        $channelStats['active']    = (int)$r['active'];
        $channelStats['errors']    = (int)$r['errors'];
    }
} catch (Throwable $e) {}

// ============================================
// SUBSCRIPTION
// ============================================
$subscription = null;
try {
    $subscription = vdQ(
        "SELECT * FROM vendor_subscriptions
         WHERE vendor_id = ?
         ORDER BY id DESC LIMIT 1",
        [$vendorId]
    );
} catch (Throwable $e) {}

// ============================================
// UNREAD COUNTS
// ============================================
$unreadMessages = 0;
$unreadNotifs = 0;

try {
    $r = vdQ(
        "SELECT COUNT(*) AS c FROM messages m
         JOIN chat_threads t ON m.thread_id = t.id
         WHERE t.vendor_id = ? AND m.sender_id != ? AND m.is_read = 0",
        [$vendorId, $userId]
    );
    if ($r) $unreadMessages = (int)$r['c'];
} catch (Throwable $e) {}

try {
    $r = vdQ(
        "SELECT COUNT(*) AS c FROM notifications
         WHERE user_id = ? AND is_read = 0",
        [$userId]
    );
    if ($r) $unreadNotifs = (int)$r['c'];
} catch (Throwable $e) {}

// ============================================
// SPARKLINE — last 14 days bookings
// ============================================
$sparkRows = vdQA(
    "SELECT DATE(created_at) AS d, COUNT(*) AS c
     FROM bookings
     WHERE vendor_id = ? AND created_at >= DATE_SUB(CURDATE(), INTERVAL 14 DAY)
     GROUP BY DATE(created_at)
     ORDER BY d ASC",
    [$vendorId]
);

$sparkMap = [];
foreach ($sparkRows as $r) $sparkMap[$r['d']] = (int)$r['c'];

$spark = [];
for ($i = 13; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $spark[] = ['date' => $d, 'count' => $sparkMap[$d] ?? 0];
}

$sparkMax = max(1, max(array_column($spark, 'count')));

$sparkPoints = [];
$sparkW = 320;
$sparkH = 60;
$stepX = $sparkW / max(1, count($spark) - 1);
foreach ($spark as $i => $d) {
    $x = $i * $stepX;
    $y = $sparkH - (($d['count'] / $sparkMax) * ($sparkH - 10)) - 5;
    $sparkPoints[] = round($x, 1) . ',' . round($y, 1);
}
$sparkPolyline = implode(' ', $sparkPoints);
$sparkArea = '0,' . $sparkH . ' ' . $sparkPolyline . ' ' . $sparkW . ',' . $sparkH;

// ============================================
// ONBOARDING CHECKLIST
// ============================================
$onboarding = [
    'has_property'  => false,
    'has_room'      => false,
    'has_published' => false,
    'has_booking'   => false,
];

try {
    $onboarding['has_property'] = (int)(vdQ(
        "SELECT COUNT(*) AS c FROM properties WHERE vendor_id = ?",
        [$vendorId]
    )['c'] ?? 0) > 0;

    if ($onboarding['has_property']) {
        $onboarding['has_room'] = (int)(vdQ(
            "SELECT COUNT(*) AS c FROM room_types
             WHERE property_id IN (SELECT id FROM properties WHERE vendor_id = ?)",
            [$vendorId]
        )['c'] ?? 0) > 0;
    }

    $onboarding['has_published'] = (int)(vdQ(
        "SELECT COUNT(*) AS c FROM properties WHERE vendor_id = ? AND status = 'published'",
        [$vendorId]
    )['c'] ?? 0) > 0;

    $onboarding['has_booking'] = (int)(vdQ(
        "SELECT COUNT(*) AS c FROM bookings WHERE vendor_id = ?",
        [$vendorId]
    )['c'] ?? 0) > 0;
} catch (Throwable $e) {}

$onboardingStepsDone = count(array_filter($onboarding));
$showOnboarding = $onboardingStepsDone < 4;

// ============================================
// RECENT BOOKINGS
// ============================================
$recentBookings = vdQA(
    "SELECT b.*, p.name AS property_name, u.first_name, u.last_name
     FROM bookings b
     LEFT JOIN properties p ON b.property_id = p.id
     LEFT JOIN users u ON b.user_id = u.id
     WHERE b.vendor_id = ?
     ORDER BY b.created_at DESC
     LIMIT 6",
    [$vendorId]
);

// ============================================
// PROPERTY PERFORMANCE
// ============================================
$propertyPerf = vdQA(
    "SELECT p.id, p.name, p.slug,
            (SELECT COUNT(*) FROM bookings WHERE property_id = p.id AND status IN ('completed','checked_out','confirmed','checked_in')) AS bookings,
            (SELECT COALESCE(SUM(total_amount),0) FROM bookings WHERE property_id = p.id AND status IN ('completed','checked_out')) AS revenue,
            p.average_rating
     FROM properties p
     WHERE p.vendor_id = ? AND p.is_active = 1
     ORDER BY revenue DESC
     LIMIT 4",
    [$vendorId]
);

// ============================================
// ALERTS
// ============================================
$alerts = [];

if ($stats['pending'] > 0) {
    $alerts[] = ['type' => 'warning', 'icon' => 'fa-clock', 'text' => $stats['pending'] . ' pending booking' . ($stats['pending'] !== 1 ? 's' : '') . ' need approval', 'url' => '/?page=vendor-bookings&view=pending'];
}
if ($extended['concierge_urgent'] > 0) {
    $alerts[] = ['type' => 'danger', 'icon' => 'fa-fire', 'text' => $extended['concierge_urgent'] . ' urgent concierge request' . ($extended['concierge_urgent'] !== 1 ? 's' : ''), 'url' => '/?page=vendor-concierge&filter=urgent'];
}
if ($extended['maintenance_open'] > 0) {
    $alerts[] = ['type' => 'warning', 'icon' => 'fa-tools', 'text' => $extended['maintenance_open'] . ' open maintenance request' . ($extended['maintenance_open'] !== 1 ? 's' : ''), 'url' => '/?page=vendor-maintenance'];
}
if ($stats['dirty_rooms'] > 0 || $extended['hk_dirty'] > 0) {
    $dirtyCount = max($stats['dirty_rooms'], $extended['hk_dirty']);
    $alerts[] = ['type' => 'info', 'icon' => 'fa-broom', 'text' => $dirtyCount . ' room' . ($dirtyCount !== 1 ? 's' : '') . ' need cleaning', 'url' => '/?page=vendor-housekeeping'];
}
if ($stats['arrivals_today'] > 0) {
    $alerts[] = ['type' => 'info', 'icon' => 'fa-sign-in-alt', 'text' => $stats['arrivals_today'] . ' arrival' . ($stats['arrivals_today'] !== 1 ? 's' : '') . ' expected today', 'url' => '/?page=vendor-booking-calendar&view=today'];
}
if ($stats['departures_today'] > 0) {
    $alerts[] = ['type' => 'info', 'icon' => 'fa-sign-out-alt', 'text' => $stats['departures_today'] . ' departure' . ($stats['departures_today'] !== 1 ? 's' : '') . ' today', 'url' => '/?page=vendor-booking-calendar&view=today'];
}
if ($backupHealth['status'] === 'critical' && $backupHealth['count'] === 0) {
    $alerts[] = ['type' => 'danger', 'icon' => 'fa-database', 'text' => 'No backups yet — protect your data', 'url' => '/?page=vendor-backup'];
}
if ($channelStats['errors'] > 0) {
    $alerts[] = ['type' => 'warning', 'icon' => 'fa-plug', 'text' => $channelStats['errors'] . ' channel sync error' . ($channelStats['errors'] !== 1 ? 's' : ''), 'url' => '/?page=vendor-channels'];
}

// ============================================
// QUICK ACTIONS — FULL LIST (28 ACTIONS)
// ============================================
$quickActionGroups = [
    'Daily Operations' => [
        ['icon' => 'fa-concierge-bell', 'label' => 'Front Desk',   'url' => '/?page=vendor-frontdesk',         'color' => '#00d4ff'],
        ['icon' => 'fa-calendar-check', 'label' => 'Bookings',     'url' => '/?page=vendor-bookings',          'color' => '#667eea'],
        ['icon' => 'fa-calendar-alt',   'label' => 'Calendar',     'url' => '/?page=vendor-booking-calendar',  'color' => '#a3bffa'],
        ['icon' => 'fa-sign-in-alt',    'label' => 'Check-In',     'url' => '/?page=vendor-checkin',           'color' => '#00b894'],
        ['icon' => 'fa-sign-out-alt',   'label' => 'Check-Out',    'url' => '/?page=vendor-checkout',          'color' => '#f6ad55'],
    ],
    'Properties' => [
        ['icon' => 'fa-building',       'label' => 'Properties',   'url' => '/?page=vendor-properties',        'color' => '#667eea'],
        ['icon' => 'fa-plus-circle',    'label' => 'Add New',      'url' => '/?page=vendor-add-property',      'color' => '#00b894'],
        ['icon' => 'fa-bed',            'label' => 'Rooms',        'url' => '/?page=vendor-rooms',             'color' => '#a3bffa'],
        ['icon' => 'fa-calendar-day',   'label' => 'Rates',        'url' => '/?page=vendor-calendar',          'color' => '#00d4ff'],
        ['icon' => 'fa-boxes',          'label' => 'Inventory',    'url' => '/?page=vendor-inventory',         'color' => '#667eea'],
    ],
    'Guest Services' => [
        ['icon' => 'fa-concierge-bell', 'label' => 'Concierge',    'url' => '/?page=vendor-concierge',         'color' => '#00b894'],
        ['icon' => 'fa-utensils',       'label' => 'Dining',       'url' => '/?page=vendor-dining',            'color' => '#f6ad55'],
        ['icon' => 'fa-broom',          'label' => 'Housekeeping', 'url' => '/?page=vendor-housekeeping',      'color' => '#00d4ff'],
        ['icon' => 'fa-tools',          'label' => 'Maintenance',  'url' => '/?page=vendor-maintenance',       'color' => '#f5576c'],
        ['icon' => 'fa-tshirt',         'label' => 'Laundry',      'url' => '/?page=vendor-laundry',           'color' => '#00b894'],
        ['icon' => 'fa-cash-register',  'label' => 'Restaurant',   'url' => '/?page=vendor-restaurant-pos',    'color' => '#f6ad55'],
    ],
    'Finance' => [
        ['icon' => 'fa-chart-line',     'label' => 'Analytics',    'url' => '/?page=vendor-analytics',         'color' => '#00d4ff'],
        ['icon' => 'fa-dollar-sign',    'label' => 'Finance',      'url' => '/?page=vendor-finance',           'color' => '#00b894'],
        ['icon' => 'fa-file-pdf',       'label' => 'Reports',      'url' => '/?page=vendor-reports',           'color' => '#00b894'],
        ['icon' => 'fa-money-bill-wave','label' => 'Payouts',      'url' => '/?page=vendor-payouts',           'color' => '#00b894'],
        ['icon' => 'fa-brain',          'label' => 'AI Forecast',  'url' => '/?page=vendor-forecasting',       'color' => '#667eea'],
    ],
    'Business Tools' => [
        ['icon' => 'fa-robot',          'label' => 'Automation',   'url' => '/?page=vendor-automation',        'color' => '#667eea'],
        ['icon' => 'fa-plug',           'label' => 'Channels',     'url' => '/?page=vendor-channels',          'color' => '#b794f4'],
        ['icon' => 'fa-database',       'label' => 'Backup',       'url' => '/?page=vendor-backup',            'color' => '#00b894'],
        ['icon' => 'fa-users-cog',      'label' => 'Staff',        'url' => '/?page=vendor-staff',             'color' => '#667eea'],
        ['icon' => 'fa-palette',        'label' => 'Theme',        'url' => '/?page=vendor-theme',             'color' => '#667eea'],
        ['icon' => 'fa-cog',            'label' => 'Settings',     'url' => '/?page=vendor-settings',          'color' => '#667eea'],
        ['icon' => 'fa-crown',          'label' => 'PMS Hub',      'url' => '/?page=vendor-pms',               'color' => '#f6ad55'],
    ],
];

require_once __DIR__ . '/../../includes/header.php';
?>

<style>
.vd-page {
    background: #0f0c29;
    min-height: 100vh;
    padding: 100px 0 60px;
    color: white;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.vd-page .container { max-width: 1300px; margin: 0 auto; padding: 0 20px; }

/* SUBSCRIPTION BANNER */
.vd-sub-banner {
    padding: 12px 20px;
    border-radius: 14px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
    font-size: 13px;
}
.vd-sub-banner.free { background: linear-gradient(135deg, rgba(102,126,234,0.1), rgba(118,75,162,0.1)); border: 1px solid rgba(102,126,234,0.3); }
.vd-sub-banner.paid { background: linear-gradient(135deg, rgba(246,173,85,0.12), rgba(237,137,54,0.08)); border: 1px solid rgba(246,173,85,0.3); }
.vd-sub-banner.warn { background: rgba(245,87,108,0.1); border: 1px solid rgba(245,87,108,0.3); }
.vd-sub-banner .info { display: flex; align-items: center; gap: 10px; color: white; }
.vd-sub-banner .info strong { color: #ffd700; }
.vd-sub-banner .info i { color: #a3bffa; font-size: 16px; }
.vd-sub-banner a { color: #a3bffa; text-decoration: none; font-weight: 700; }
.vd-sub-banner a:hover { text-decoration: underline; }

/* HERO */
.vd-hero {
    background: linear-gradient(135deg, rgba(102,126,234,0.15), rgba(118,75,162,0.15));
    border: 1px solid rgba(102,126,234,0.3);
    border-radius: 20px;
    padding: 28px 32px;
    margin-bottom: 24px;
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 24px;
    align-items: center;
}
@media (max-width: 800px) { .vd-hero { grid-template-columns: 1fr; } }
.vd-hero h1 {
    font-size: 30px;
    font-weight: 800;
    margin-bottom: 6px;
    background: linear-gradient(135deg, #fff, #a3bffa);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}
.vd-hero p { color: #a0aec0; font-size: 14px; }
.vd-hero .today-strip { display: flex; gap: 24px; margin-top: 14px; flex-wrap: wrap; }
.vd-hero .today-strip .item { display: flex; align-items: center; gap: 8px; font-size: 13px; color: #cbd5e0; }
.vd-hero .today-strip .item i { color: #00d4ff; }
.vd-hero .today-strip .item strong { color: white; }
.vd-hero-actions { display: flex; gap: 10px; flex-wrap: wrap; }

.vd-btn {
    padding: 11px 22px;
    border-radius: 10px;
    text-decoration: none;
    font-weight: 700;
    font-size: 13px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.25s;
    white-space: nowrap;
    position: relative;
}
.vd-btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
.vd-btn-primary:hover { transform: translateY(-2px); box-shadow: 0 10px 30px rgba(102,126,234,0.4); color: white; }
.vd-btn-outline { background: rgba(255,255,255,0.05); color: #cbd5e0; border: 1px solid rgba(255,255,255,0.12); }
.vd-btn-outline:hover { background: rgba(255,255,255,0.1); color: white; }
.vd-btn .badge {
    position: absolute;
    top: -6px;
    right: -6px;
    background: #f5576c;
    color: white;
    font-size: 10px;
    font-weight: 800;
    min-width: 18px;
    height: 18px;
    border-radius: 50px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0 5px;
    border: 2px solid #0f0c29;
}

/* ONBOARDING */
.vd-onboard {
    background: linear-gradient(135deg, rgba(0,212,255,0.08), rgba(102,126,234,0.08));
    border: 1px solid rgba(0,212,255,0.25);
    border-radius: 20px;
    padding: 24px 28px;
    margin-bottom: 24px;
}
.vd-onboard-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;
    flex-wrap: wrap;
}
.vd-onboard-head h2 { font-size: 20px; font-weight: 800; margin-bottom: 4px; display: flex; align-items: center; gap: 10px; }
.vd-onboard-head p { color: #a0aec0; font-size: 13px; }
.vd-onboard-head p strong { color: white; }
.vd-onboard-progress { position: relative; width: 60px; height: 60px; flex-shrink: 0; }
.vd-onboard-pct {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 14px;
    color: #00d4ff;
}
.vd-onboard-steps { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; }
.vd-onboard-step {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 16px;
    border-radius: 12px;
    background: rgba(0,0,0,0.2);
    border: 1px solid rgba(255,255,255,0.08);
    text-decoration: none;
    color: white;
    transition: all 0.25s;
}
.vd-onboard-step.active {
    background: rgba(102,126,234,0.1);
    border-color: rgba(102,126,234,0.4);
    box-shadow: 0 0 0 3px rgba(102,126,234,0.08);
}
.vd-onboard-step.active:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(102,126,234,0.25); }
.vd-onboard-step.done { opacity: 0.7; background: rgba(0,184,148,0.06); border-color: rgba(0,184,148,0.25); }
.vd-onboard-step.locked { opacity: 0.4; cursor: not-allowed; pointer-events: none; }
.vd-onboard-step .step-icon {
    width: 40px; height: 40px; border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px; flex-shrink: 0;
    background: rgba(102,126,234,0.15); color: #a3bffa;
}
.vd-onboard-step.active .step-icon { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
.vd-onboard-step.done .step-icon { background: rgba(0,184,148,0.2); color: #00b894; }
.vd-onboard-step .step-body { flex: 1; min-width: 0; }
.vd-onboard-step .step-title { font-size: 13px; font-weight: 700; margin-bottom: 2px; }
.vd-onboard-step .step-desc { font-size: 11px; color: #a0aec0; line-height: 1.4; }
.vd-onboard-step.done .step-title { text-decoration: line-through; text-decoration-color: rgba(255,255,255,0.3); }
.vd-onboard-step .step-arrow { color: #718096; font-size: 12px; flex-shrink: 0; }
.vd-onboard-step.active .step-arrow { color: #a3bffa; }
@media (max-width: 700px) { .vd-onboard-steps { grid-template-columns: 1fr; } .vd-onboard-head h2 { font-size: 17px; } }

/* ALERTS */
.vd-alerts { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 10px; margin-bottom: 24px; }
.vd-alert {
    display: flex; align-items: center; gap: 12px;
    padding: 12px 16px; border-radius: 12px;
    text-decoration: none; font-size: 13px; font-weight: 600;
    color: white; transition: transform 0.2s;
    background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08);
    position: relative; overflow: hidden;
}
.vd-alert::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; }
.vd-alert.warning::before { background: #f6ad55; }
.vd-alert.info::before { background: #00d4ff; }
.vd-alert.danger::before { background: #f5576c; }
.vd-alert:hover { transform: translateY(-2px); border-color: rgba(102,126,234,0.4); color: white; }
.vd-alert i { font-size: 15px; }
.vd-alert.warning i { color: #f6ad55; }
.vd-alert.info i { color: #00d4ff; }
.vd-alert.danger i { color: #f5576c; }

/* KPI */
.vd-stats { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
.vd-stat {
    background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08);
    border-radius: 16px; padding: 20px; transition: all 0.25s;
    position: relative; overflow: hidden;
    text-decoration: none; color: white; display: block;
}
.vd-stat:hover { transform: translateY(-4px); border-color: rgba(102,126,234,0.35); box-shadow: 0 12px 32px rgba(0,0,0,0.25); color: white; }
.vd-stat .icon { width: 42px; height: 42px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 17px; color: white; margin-bottom: 12px; }
.vd-stat .value { font-size: 26px; font-weight: 800; color: white; line-height: 1.1; margin-bottom: 2px; }
.vd-stat .value small { font-size: 15px; color: #a0aec0; font-weight: 600; }
.vd-stat .label { color: #a0aec0; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; font-weight: 700; }
.vd-stat .sub { font-size: 11px; color: #718096; margin-top: 6px; }
.vd-stat .trend { font-size: 11px; font-weight: 700; }
.vd-stat .trend.up { color: #00b894; }
.vd-stat .trend.down { color: #f5576c; }

/* HEALTH STRIP */
.vd-health { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin-bottom: 24px; }
.vd-health-item {
    background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08);
    border-radius: 12px; padding: 14px 16px;
    display: flex; align-items: center; gap: 12px;
    text-decoration: none; color: white; transition: all 0.2s;
}
.vd-health-item:hover { border-color: rgba(102,126,234,0.4); color: white; }
.vd-health-item .indicator { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
.vd-health-item .indicator.good { background: #00b894; box-shadow: 0 0 8px rgba(0,184,148,0.6); }
.vd-health-item .indicator.warn { background: #f6ad55; box-shadow: 0 0 8px rgba(246,173,85,0.6); }
.vd-health-item .indicator.critical { background: #f5576c; box-shadow: 0 0 8px rgba(245,87,108,0.6); }
.vd-health-item .info { flex: 1; }
.vd-health-item .info .label { font-size: 11px; color: #a0aec0; text-transform: uppercase; letter-spacing: 0.04em; font-weight: 700; }
.vd-health-item .info .value { font-size: 13px; font-weight: 700; margin-top: 2px; }

/* SPARKLINE */
.vd-spark-card {
    background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08);
    border-radius: 16px; padding: 20px 24px; margin-bottom: 24px;
    display: grid; grid-template-columns: 1fr auto; gap: 20px; align-items: center;
}
@media (max-width: 700px) { .vd-spark-card { grid-template-columns: 1fr; } }
.vd-spark-card .head { font-size: 13px; color: #a0aec0; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 700; margin-bottom: 6px; }
.vd-spark-card .total { font-size: 24px; font-weight: 800; color: white; }
.vd-spark-card .total small { color: #a0aec0; font-weight: 500; font-size: 13px; }
.vd-spark-svg { width: 100%; max-width: 340px; height: 64px; }
.vd-spark-svg polyline { fill: none; stroke: url(#sparkGrad); stroke-width: 2.5; stroke-linecap: round; stroke-linejoin: round; }
.vd-spark-svg polygon { fill: url(#sparkAreaGrad); }
.vd-spark-labels { display: flex; justify-content: space-between; font-size: 10px; color: #718096; margin-top: 6px; max-width: 340px; }

/* SECTION */
.vd-section { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 24px; margin-bottom: 24px; }
.vd-section h2 { font-size: 17px; font-weight: 700; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
.vd-section h2 .count { background: rgba(102,126,234,0.2); color: #a3bffa; padding: 2px 10px; border-radius: 50px; font-size: 12px; font-weight: 700; }
.vd-section h2 .view-all { margin-left: auto; font-size: 12px; color: #a0aec0; text-decoration: none; font-weight: 600; }
.vd-section h2 .view-all:hover { color: #667eea; }

/* QUICK ACTIONS */
.vd-qa-group-title {
    font-size: 10px; text-transform: uppercase; letter-spacing: 0.1em;
    color: #718096; font-weight: 800; margin: 16px 0 10px;
}
.vd-qa-group-title:first-child { margin-top: 0; }
.vd-qa-row { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; margin-bottom: 8px; }
.vd-action-card {
    background: rgba(0,0,0,0.25); border: 1px solid rgba(255,255,255,0.08);
    border-radius: 12px; padding: 14px 12px; text-align: center;
    text-decoration: none; color: white; transition: all 0.25s; position: relative;
}
.vd-action-card:hover { transform: translateY(-3px); border-color: rgba(102,126,234,0.4); color: white; background: rgba(102,126,234,0.08); }
.vd-action-card i { font-size: 20px; display: block; margin-bottom: 6px; }
.vd-action-card span { font-size: 12px; font-weight: 600; }
.vd-action-card .badge {
    position: absolute; top: 6px; right: 6px;
    background: #f5576c; color: white; font-size: 9px; font-weight: 800;
    min-width: 16px; height: 16px; border-radius: 50px;
    display: inline-flex; align-items: center; justify-content: center; padding: 0 4px;
}

/* TABLE */
.vd-table { width: 100%; border-collapse: collapse; }
.vd-table th {
    text-align: left; padding: 10px 12px;
    font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em;
    color: #a0aec0; border-bottom: 1px solid rgba(255,255,255,0.08); font-weight: 700;
}
.vd-table td { padding: 12px; font-size: 13px; border-bottom: 1px solid rgba(255,255,255,0.03); vertical-align: middle; }
.vd-table tr:hover td { background: rgba(255,255,255,0.02); }
.vd-table tr:last-child td { border-bottom: none; }

.guest-row { display: flex; align-items: center; gap: 10px; }
.guest-avatar {
    width: 32px; height: 32px; border-radius: 50%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex; align-items: center; justify-content: center;
    font-weight: 800; font-size: 12px; color: white; flex-shrink: 0;
}
.guest-meta { min-width: 0; }
.guest-meta .name { font-weight: 600; font-size: 13px; }
.guest-meta .ref { font-size: 10px; color: #718096; font-family: monospace; }

.pill {
    padding: 3px 10px; border-radius: 50px; font-size: 10px; font-weight: 700;
    text-transform: uppercase; letter-spacing: 0.03em; display: inline-block;
}
.pill.pending { background: rgba(246,173,85,0.2); color: #f6ad55; }
.pill.confirmed { background: rgba(102,126,234,0.2); color: #a3bffa; }
.pill.checked_in { background: rgba(0,184,148,0.2); color: #00b894; }
.pill.completed, .pill.checked_out { background: rgba(0,212,255,0.2); color: #00d4ff; }
.pill.cancelled, .pill.no_show { background: rgba(245,87,108,0.2); color: #f5576c; }

/* PROPERTY PERFORMANCE */
.vd-prop-row { display: grid; grid-template-columns: 1fr auto auto; gap: 14px; align-items: center; padding: 14px 0; border-bottom: 1px solid rgba(255,255,255,0.04); }
.vd-prop-row:last-child { border-bottom: none; }
.vd-prop-row .name { font-weight: 700; font-size: 14px; color: white; text-decoration: none; }
.vd-prop-row .name:hover { color: #a3bffa; }
.vd-prop-row .meta { font-size: 11px; color: #718096; margin-top: 2px; }
.vd-prop-row .bar { width: 80px; height: 6px; background: rgba(255,255,255,0.06); border-radius: 3px; overflow: hidden; }
.vd-prop-row .bar .fill { height: 100%; background: linear-gradient(90deg, #667eea, #764ba2); border-radius: 3px; }
.vd-prop-row .rev { font-weight: 800; color: #00d4ff; font-size: 14px; text-align: right; white-space: nowrap; }

/* EMPTY */
.vd-empty { padding: 40px 20px; text-align: center; color: #718096; font-size: 13px; }
.vd-empty i { font-size: 36px; opacity: 0.3; display: block; margin-bottom: 10px; }

/* 2-COL */
.vd-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
@media (max-width: 900px) { .vd-grid-2 { grid-template-columns: 1fr; } }
</style>

<div class="vd-page">
    <div class="container">

        <!-- SUBSCRIPTION BANNER -->
        <?php if ($subscription):
            $subStatus = strtolower($subscription['status'] ?? 'active');
            $subPlan = $subscription['plan'] ?? $subscription['plan_name'] ?? 'Standard';
            $subEnds = $subscription['ends_at'] ?? $subscription['expires_at'] ?? null;
            $daysLeft = $subEnds ? (int)floor((strtotime($subEnds) - time()) / 86400) : null;
            $bannerClass = 'free';
            if ($subStatus === 'active' && $daysLeft !== null) {
                $bannerClass = $daysLeft < 7 ? 'warn' : 'paid';
            }
        ?>
            <div class="vd-sub-banner <?= $bannerClass ?>">
                <div class="info">
                    <i class="fas fa-crown"></i>
                    <span>
                        <strong><?= htmlspecialchars(ucfirst($subPlan)) ?> Plan</strong>
                        <?php if ($subEnds): ?>
                            · <?= $daysLeft !== null && $daysLeft >= 0 ? "renews in $daysLeft day" . ($daysLeft === 1 ? '' : 's') : 'expired' ?>
                        <?php endif; ?>
                    </span>
                </div>
                <a href="/?page=vendor-subscription">Manage Subscription →</a>
            </div>
        <?php elseif ($stats['properties'] === 0): ?>
            <div class="vd-sub-banner free">
                <div class="info">
                    <i class="fas fa-gift"></i>
                    <span>You're on the <strong>Free plan</strong> — no credit card required.</span>
                </div>
                <a href="/?page=vendor-subscription">View Plans →</a>
            </div>
        <?php endif; ?>

        <!-- HERO -->
        <div class="vd-hero">
            <div>
                <h1>Welcome back, <?= htmlspecialchars($vendor['company_name'] ?? 'Vendor') ?></h1>
                <p>
                    <?= date('l, F j, Y') ?>
                    · <strong style="color:#a3bffa;"><?= $stats['properties'] ?></strong> active propert<?= $stats['properties'] === 1 ? 'y' : 'ies' ?>
                    · <strong style="color:#a3bffa;"><?= $stats['rooms_total'] ?></strong> room<?= $stats['rooms_total'] === 1 ? '' : 's' ?>
                </p>

                <div class="today-strip">
                    <div class="item">
                        <i class="fas fa-sign-in-alt"></i>
                        <span><strong><?= $stats['arrivals_today'] ?></strong> arrivals</span>
                    </div>
                    <div class="item">
                        <i class="fas fa-sign-out-alt"></i>
                        <span><strong><?= $stats['departures_today'] ?></strong> departures</span>
                    </div>
                    <div class="item">
                        <i class="fas fa-user-check"></i>
                        <span><strong><?= $stats['checked_in'] ?></strong> in house</span>
                    </div>
                    <div class="item">
                        <i class="fas fa-dollar-sign"></i>
                        <span><strong><?= vdMoney($stats['revenue_today'], $baseCurrency) ?></strong> earned today</span>
                    </div>
                </div>
            </div>

            <div class="vd-hero-actions">
                <a href="/?page=vendor-bookings" class="vd-btn vd-btn-outline">
                    <i class="fas fa-calendar-check"></i> Bookings
                    <?php if ($stats['pending'] > 0): ?>
                        <span class="badge"><?= $stats['pending'] ?></span>
                    <?php endif; ?>
                </a>
                <?php if ($unreadMessages > 0): ?>
                    <a href="/?page=vendor-messages" class="vd-btn vd-btn-outline">
                        <i class="fas fa-comments"></i> Messages
                        <span class="badge"><?= $unreadMessages ?></span>
                    </a>
                <?php endif; ?>
                <a href="/?page=vendor-add-property" class="vd-btn vd-btn-primary">
                    <i class="fas fa-plus-circle"></i> Add Property
                </a>
            </div>
        </div>

        <!-- ONBOARDING CHECKLIST -->
        <?php if ($showOnboarding): ?>
        <div class="vd-onboard">
            <div class="vd-onboard-head">
                <div>
                    <h2><i class="fas fa-rocket" style="color:#00d4ff;"></i> Get Your Property Live</h2>
                    <p>Complete these <strong><?= 4 - $onboardingStepsDone ?></strong> step<?= (4 - $onboardingStepsDone) === 1 ? '' : 's' ?> to start receiving bookings</p>
                </div>
                <div class="vd-onboard-progress">
                    <svg width="60" height="60" viewBox="0 0 60 60">
                        <?php
                        $circumference = 2 * 3.14159 * 26;
                        $offset = $circumference - ($circumference * ($onboardingStepsDone / 4));
                        ?>
                        <circle cx="30" cy="30" r="26" fill="none" stroke="rgba(255,255,255,0.08)" stroke-width="4"/>
                        <circle cx="30" cy="30" r="26" fill="none" stroke="url(#obGrad)" stroke-width="4"
                                stroke-dasharray="<?= round($circumference, 2) ?>"
                                stroke-dashoffset="<?= round($offset, 2) ?>"
                                stroke-linecap="round"
                                transform="rotate(-90 30 30)"/>
                        <defs>
                            <linearGradient id="obGrad" x1="0%" y1="0%" x2="100%" y2="100%">
                                <stop offset="0%" stop-color="#00d4ff"/>
                                <stop offset="100%" stop-color="#667eea"/>
                            </linearGradient>
                        </defs>
                    </svg>
                    <div class="vd-onboard-pct"><?= $onboardingStepsDone ?>/4</div>
                </div>
            </div>

            <div class="vd-onboard-steps">
                <a href="<?= $onboarding['has_property'] ? '/?page=vendor-properties' : '/?page=vendor-add-property' ?>"
                   class="vd-onboard-step <?= $onboarding['has_property'] ? 'done' : 'active' ?>">
                    <div class="step-icon"><i class="fas fa-<?= $onboarding['has_property'] ? 'check' : 'building' ?>"></i></div>
                    <div class="step-body">
                        <div class="step-title">Create your first property</div>
                        <div class="step-desc">Add the building or villa you want to list</div>
                    </div>
                    <div class="step-arrow"><i class="fas fa-chevron-right"></i></div>
                </a>

                <a href="<?= $onboarding['has_room'] ? '/?page=vendor-rooms' : '/?page=vendor-properties' ?>"
                   class="vd-onboard-step <?= $onboarding['has_room'] ? 'done' : ($onboarding['has_property'] ? 'active' : 'locked') ?>">
                    <div class="step-icon"><i class="fas fa-<?= $onboarding['has_room'] ? 'check' : 'bed' ?>"></i></div>
                    <div class="step-body">
                        <div class="step-title">Add room types</div>
                        <div class="step-desc">Standard, Deluxe, Suite — each becomes bookable</div>
                    </div>
                    <div class="step-arrow"><i class="fas fa-chevron-right"></i></div>
                </a>

                <a href="/?page=vendor-properties"
                   class="vd-onboard-step <?= $onboarding['has_published'] ? 'done' : ($onboarding['has_room'] ? 'active' : 'locked') ?>">
                    <div class="step-icon"><i class="fas fa-<?= $onboarding['has_published'] ? 'check' : 'globe' ?>"></i></div>
                    <div class="step-body">
                        <div class="step-title">Publish your listing</div>
                        <div class="step-desc">Make it visible to travellers searching</div>
                    </div>
                    <div class="step-arrow"><i class="fas fa-chevron-right"></i></div>
                </a>

                <div class="vd-onboard-step <?= $onboarding['has_booking'] ? 'done' : ($onboarding['has_published'] ? 'active' : 'locked') ?>">
                    <div class="step-icon"><i class="fas fa-<?= $onboarding['has_booking'] ? 'check' : 'calendar-check' ?>"></i></div>
                    <div class="step-body">
                        <div class="step-title">Receive your first booking</div>
                        <div class="step-desc">Share your listing link or wait for organic traffic</div>
                    </div>
                    <div class="step-arrow">
                        <?php if ($onboarding['has_booking']): ?><i class="fas fa-check-circle" style="color:#00b894;"></i><?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- ALERTS -->
        <?php if (!empty($alerts)): ?>
        <div class="vd-alerts">
            <?php foreach ($alerts as $a): ?>
                <a href="<?= htmlspecialchars($a['url']) ?>" class="vd-alert <?= $a['type'] ?>">
                    <i class="fas <?= $a['icon'] ?>"></i>
                    <span><?= htmlspecialchars($a['text']) ?></span>
                    <i class="fas fa-chevron-right" style="margin-left:auto; font-size:11px; opacity:0.5;"></i>
                </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- KPI GRID (6 tiles) -->
        <div class="vd-stats">
            <div class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #667eea, #764ba2);"><i class="fas fa-building"></i></div>
                <div class="value"><?= number_format($stats['properties']) ?></div>
                <div class="label">Properties</div>
                <div class="sub"><?= $stats['rooms_total'] ?> rooms active</div>
            </div>

            <div class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #00d4ff, #00b894);"><i class="fas fa-calendar-check"></i></div>
                <div class="value"><?= number_format($stats['bookings_total']) ?></div>
                <div class="label">Total Bookings</div>
                <div class="sub"><span class="trend up">+<?= $stats['bookings_month'] ?></span> this month</div>
            </div>

            <div class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #00b894, #00d4ff);"><i class="fas fa-dollar-sign"></i></div>
                <div class="value"><?= vdMoney($stats['revenue_total'], $baseCurrency) ?></div>
                <div class="label">Total Revenue</div>
                <div class="sub"><?= vdMoney($stats['revenue_month'], $baseCurrency) ?> this month</div>
            </div>

            <div class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #f093fb, #f5576c);"><i class="fas fa-percentage"></i></div>
                <div class="value"><?= $stats['occupancy'] ?><small>%</small></div>
                <div class="label">Occupancy</div>
                <div class="sub"><?= $roomsBookedNow ?> of <?= $stats['rooms_total'] ?> rooms</div>
            </div>

            <div class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #f6ad55, #ed8936);"><i class="fas fa-clock"></i></div>
                <div class="value"><?= number_format($stats['pending']) ?></div>
                <div class="label">Pending Approvals</div>
                <div class="sub"><?= $stats['pending'] > 0 ? 'Needs attention' : 'All clear ✓' ?></div>
            </div>

            <div class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #a3bffa, #667eea);"><i class="fas fa-chart-line"></i></div>
                <div class="value"><?= vdMoney($stats['avg_rate'], $baseCurrency) ?></div>
                <div class="label">Avg Nightly Rate</div>
                <div class="sub">ADR across all bookings</div>
            </div>
        </div>

        <!-- EXTENDED KPI ROW -->
        <div class="vd-stats">
            <a href="/?page=vendor-concierge&filter=active" class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #00b894, #00d4ff);"><i class="fas fa-concierge-bell"></i></div>
                <div class="value">
                    <?= number_format($extended['concierge_pending']) ?>
                    <?php if ($extended['concierge_urgent'] > 0): ?>
                        <small style="color:#f5576c;">· <?= $extended['concierge_urgent'] ?> urgent</small>
                    <?php endif; ?>
                </div>
                <div class="label">Concierge Requests</div>
                <div class="sub"><?= $extended['concierge_pending'] > 0 ? 'Needs attention' : 'All clear ✓' ?></div>
            </a>

            <a href="/?page=vendor-dining" class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #f6ad55, #ed8936);"><i class="fas fa-utensils"></i></div>
                <div class="value"><?= number_format($extended['dining_today']) ?></div>
                <div class="label">Dining Today</div>
                <div class="sub"><?= $extended['dining_covers'] ?> covers booked</div>
            </a>

            <a href="/?page=vendor-housekeeping" class="vd-stat">
                <div class="icon" style="background: linear-gradient(135deg, #a3bffa, #667eea);"><i class="fas fa-broom"></i></div>
                <div class="value"><?= number_format($extended['hk_dirty']) ?></div>
                <div class="label">Rooms to Clean</div>
                <div class="sub"><?= $extended['hk_occupied'] ?> occupied</div>
            </a>
        </div>

        <!-- HEALTH STRIP -->
        <div class="vd-health">
            <a href="/?page=vendor-backup" class="vd-health-item">
                <div class="indicator <?= $backupHealth['status'] === 'good' ? 'good' : ($backupHealth['status'] === 'warn' ? 'warn' : 'critical') ?>"></div>
                <div class="info">
                    <div class="label">Backups</div>
                    <div class="value">
                        <?php if ($backupHealth['count'] === 0): ?>
                            No backups yet
                        <?php else: ?>
                            <?= $backupHealth['count'] ?> backup<?= $backupHealth['count'] === 1 ? '' : 's' ?>
                            <?php if ($backupHealth['days_since'] !== null): ?> · <?= $backupHealth['days_since'] ?>d old<?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </a>

            <a href="/?page=vendor-channels" class="vd-health-item">
                <div class="indicator <?= $channelStats['errors'] > 0 ? 'critical' : ($channelStats['active'] > 0 ? 'good' : 'warn') ?>"></div>
                <div class="info">
                    <div class="label">Channels</div>
                    <div class="value">
                        <?= $channelStats['active'] ?> active
                        <?php if ($channelStats['errors'] > 0): ?> · <?= $channelStats['errors'] ?> error<?php endif; ?>
                    </div>
                </div>
            </a>

            <a href="/?page=vendor-messages" class="vd-health-item">
                <div class="indicator <?= $unreadMessages > 0 ? 'warn' : 'good' ?>"></div>
                <div class="info">
                    <div class="label">Messages</div>
                    <div class="value"><?= $unreadMessages > 0 ? $unreadMessages . ' unread' : 'All read' ?></div>
                </div>
            </a>

            <a href="/?page=notifications" class="vd-health-item">
                <div class="indicator <?= $unreadNotifs > 0 ? 'warn' : 'good' ?>"></div>
                <div class="info">
                    <div class="label">Notifications</div>
                    <div class="value"><?= $unreadNotifs > 0 ? $unreadNotifs . ' new' : 'Up to date' ?></div>
                </div>
            </a>
        </div>

        <!-- SPARKLINE -->
        <div class="vd-spark-card">
            <div>
                <div class="head">Bookings · Last 14 Days</div>
                <div class="total">
                    <?= array_sum(array_column($spark, 'count')) ?>
                    <small>total</small>
                </div>
                <div style="font-size: 11px; color: #718096; margin-top: 4px;">
                    Peak: <strong style="color:#00d4ff;"><?= $sparkMax ?></strong> bookings in a day
                </div>
            </div>
            <div>
                <svg class="vd-spark-svg" viewBox="0 0 320 60" preserveAspectRatio="none">
                    <defs>
                        <linearGradient id="sparkGrad" x1="0" y1="0" x2="1" y2="0">
                            <stop offset="0%" stop-color="#667eea"/>
                            <stop offset="100%" stop-color="#00d4ff"/>
                        </linearGradient>
                        <linearGradient id="sparkAreaGrad" x1="0" y1="0" x2="0" y2="1">
                            <stop offset="0%" stop-color="rgba(102,126,234,0.35)"/>
                            <stop offset="100%" stop-color="rgba(102,126,234,0)"/>
                        </linearGradient>
                    </defs>
                    <polygon points="<?= htmlspecialchars($sparkArea) ?>"/>
                    <polyline points="<?= htmlspecialchars($sparkPolyline) ?>"/>
                </svg>
                <div class="vd-spark-labels">
                    <span><?= date('M d', strtotime($spark[0]['date'])) ?></span>
                    <span>Today</span>
                </div>
            </div>
        </div>

        <!-- QUICK ACTIONS -->
        <div class="vd-section">
            <h2><i class="fas fa-bolt" style="color:#667eea;"></i> Quick Actions</h2>

            <?php foreach ($quickActionGroups as $groupName => $items): ?>
                <div class="vd-qa-group-title"><?= htmlspecialchars($groupName) ?></div>
                <div class="vd-qa-row">
                    <?php foreach ($items as $item): ?>
                        <a href="<?= htmlspecialchars($item['url']) ?>" class="vd-action-card">
                            <i class="fas <?= $item['icon'] ?>" style="color: <?= $item['color'] ?>;"></i>
                            <span><?= htmlspecialchars($item['label']) ?></span>
                            <?php
                            $badge = null;
                            if ($item['label'] === 'Bookings' && $stats['pending'] > 0) $badge = $stats['pending'];
                            if ($item['label'] === 'Concierge' && $extended['concierge_pending'] > 0) $badge = $extended['concierge_pending'];
                            if ($item['label'] === 'Dining' && $extended['dining_today'] > 0) $badge = $extended['dining_today'];
                            if ($item['label'] === 'Housekeeping' && $extended['hk_dirty'] > 0) $badge = $extended['hk_dirty'];
                            if ($item['label'] === 'Maintenance' && $extended['maintenance_open'] > 0) $badge = $extended['maintenance_open'];
                            if ($item['label'] === 'Laundry' && $extended['laundry_active'] > 0) $badge = $extended['laundry_active'];
                            ?>
                            <?php if ($badge): ?><span class="badge"><?= $badge ?></span><?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- RECENT BOOKINGS + PROPERTY PERFORMANCE -->
        <div class="vd-grid-2">

            <!-- Recent Bookings -->
            <div class="vd-section">
                <h2>
                    <i class="fas fa-history" style="color:#667eea;"></i>
                    Recent Bookings
                    <span class="count"><?= count($recentBookings) ?></span>
                    <a href="/?page=vendor-bookings" class="view-all">View all →</a>
                </h2>

                <?php if (!empty($recentBookings)): ?>
                    <div style="overflow-x: auto;">
                        <table class="vd-table">
                            <thead>
                                <tr>
                                    <th>Guest</th>
                                    <th>Check-in</th>
                                    <th style="text-align:right;">Amount</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentBookings as $b):
                                    $guestName = trim(($b['first_name'] ?? '') . ' ' . ($b['last_name'] ?? '')) ?: ($b['guest_name'] ?? 'Guest');
                                    $status = $b['status'] ?? 'pending';
                                    $cur = $b['currency'] ?: ($b['base_currency'] ?: $baseCurrency);
                                ?>
                                    <tr>
                                        <td>
                                            <div class="guest-row">
                                                <div class="guest-avatar"><?= vdInitials($guestName) ?></div>
                                                <div class="guest-meta">
                                                    <div class="name"><?= htmlspecialchars($guestName) ?></div>
                                                    <div class="ref"><?= htmlspecialchars($b['booking_reference'] ?? '') ?></div>
                                                </div>
                                            </div>
                                        </td>
                                        <td style="font-size:12px;"><?= !empty($b['check_in']) ? date('M d', strtotime($b['check_in'])) : '—' ?></td>
                                        <td style="text-align:right; font-weight:700; color:#00d4ff;"><?= vdMoney($b['total_amount'] ?? 0, $cur) ?></td>
                                        <td><span class="pill <?= htmlspecialchars($status) ?>"><?= ucfirst(str_replace('_', ' ', $status)) ?></span></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <div class="vd-empty">
                        <i class="fas fa-calendar-times"></i>
                        <p>No bookings yet.</p>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Property Performance -->
            <div class="vd-section">
                <h2>
                    <i class="fas fa-chart-bar" style="color:#00d4ff;"></i>
                    Property Performance
                    <a href="/?page=vendor-properties" class="view-all">Manage →</a>
                </h2>

                <?php if (!empty($propertyPerf)): ?>
                    <?php
                    $maxRev = max(1, max(array_column($propertyPerf, 'revenue')));
                    foreach ($propertyPerf as $p):
                        $rev = (float)$p['revenue'];
                        $pct = $maxRev > 0 ? ($rev / $maxRev) * 100 : 0;
                    ?>
                        <div class="vd-prop-row">
                            <div>
                                <a href="/?page=vendor-edit-property&id=<?= (int)$p['id'] ?>" class="name">
                                    <?= htmlspecialchars($p['name'] ?? 'Unnamed') ?>
                                </a>
                                <div class="meta">
                                    <?= (int)($p['bookings'] ?? 0) ?> booking<?= (int)($p['bookings'] ?? 0) === 1 ? '' : 's' ?>
                                    <?php if ((float)($p['average_rating'] ?? 0) > 0): ?>
                                        · <?= number_format((float)$p['average_rating'], 1) ?>★
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="bar"><div class="fill" style="width: <?= round($pct, 1) ?>%;"></div></div>
                            <div class="rev"><?= vdMoney($rev, $baseCurrency) ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="vd-empty">
                        <i class="fas fa-building"></i>
                        <p>No property data yet.</p>
                    </div>
                <?php endif; ?>
            </div>

        </div>

    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>