<?php
declare(strict_types=1);

function hv5_owner_property_ids(int $userId): array {
    if (!hv5_table_exists('property_owners')) return [];
    $stmt = db()->prepare('SELECT property_id FROM property_owners WHERE user_id=?');
    $stmt->execute([$userId]);
    return array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN) ?: []);
}

function hv5_owner_dashboard(int $userId): array {
    $pids = hv5_owner_property_ids($userId);
    if (!$pids) {
        return ['properties' => 0, 'message' => 'No properties linked to your owner account. Contact admin.'];
    }
    $in = implode(',', array_fill(0, count($pids), '?'));
    $pdo = db();
    $monthStart = date('Y-m-01');

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM bookings WHERE property_id IN ($in) AND status IN ('confirmed','checked_in')");
    $stmt->execute($pids);
    $active = (int)$stmt->fetchColumn();

    $stmt = $pdo->prepare("SELECT COALESCE(SUM(total),0) FROM bookings WHERE property_id IN ($in) AND status NOT IN ('cancelled','no_show') AND check_in >= ?");
    $stmt->execute(array_merge($pids, [$monthStart]));
    $revenue = (float)$stmt->fetchColumn();

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM tickets t WHERE t.property_id IN ($in) AND t.status NOT IN ('completed','cancelled')");
    $stmt->execute($pids);
    $openTickets = (int)$stmt->fetchColumn();

    $upcoming = $pdo->prepare("SELECT b.reference, b.guest_name, b.check_in, b.check_out, p.name AS property_name, b.status, b.source
        FROM bookings b JOIN properties p ON p.id=b.property_id
        WHERE b.property_id IN ($in) AND b.check_in >= CURDATE() AND b.status NOT IN ('cancelled','no_show')
        ORDER BY b.check_in LIMIT 10");
    $upcoming->execute($pids);

    $statements = [];
    if (hv5_table_exists('owner_statements')) {
        $st = $pdo->prepare("SELECT os.*, p.name FROM owner_statements os JOIN properties p ON p.id=os.property_id WHERE os.property_id IN ($in) ORDER BY os.period_start DESC LIMIT 5");
        $st->execute($pids);
        $statements = $st->fetchAll();
    }

    $insights = function_exists('hv4_generate_insights') ? hv4_generate_insights() : [];

    return [
        'properties' => count($pids),
        'active_bookings' => $active,
        'revenue_mtd' => $revenue,
        'open_maintenance' => $openTickets,
        'upcoming' => $upcoming->fetchAll(),
        'statements' => $statements,
        'insights' => array_slice($insights, 0, 5),
    ];
}
