<?php
/**
 * V5 Owner / Client portal API
 */
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$user = current_user();
$section = $d['section'] ?? $_GET['section'] ?? 'dashboard';

if (($user['role_name'] ?? '') !== 'owner' && ($user['role_name'] ?? '') !== 'super_admin') {
    require_permission('owner.portal');
}

if ($method === 'GET') {
    if ($section === 'dashboard' || $section === '') {
        if (!function_exists('hv5_owner_dashboard')) json_error('Run V5 migration', 503);
        json_ok(hv5_owner_dashboard((int)$user['id']));
    }
    if ($section === 'bookings') {
        require_permission('owner.bookings');
        $pids = function_exists('hv5_owner_property_ids') ? hv5_owner_property_ids((int)$user['id']) : [];
        if (!$pids) json_ok([]);
        $in = implode(',', array_fill(0, count($pids), '?'));
        $stmt = db()->prepare("SELECT b.*, p.name AS property_name FROM bookings b JOIN properties p ON p.id=b.property_id WHERE b.property_id IN ($in) ORDER BY b.check_in DESC LIMIT 100");
        $stmt->execute($pids);
        json_ok($stmt->fetchAll());
    }
    if ($section === 'financial') {
        require_permission('owner.finance');
        $data = ['statements' => [], 'analytics' => []];
        if (function_exists('api') || true) {
            $pids = hv5_owner_property_ids((int)$user['id']);
            if ($pids && function_exists('hv5_table_exists') && hv5_table_exists('owner_statements')) {
                $in = implode(',', array_fill(0, count($pids), '?'));
                $st = db()->prepare("SELECT os.*, p.name AS property_name FROM owner_statements os JOIN properties p ON p.id=os.property_id WHERE os.property_id IN ($in) ORDER BY period_start DESC");
                $st->execute($pids);
                $data['statements'] = $st->fetchAll();
            }
        }
        json_ok($data);
    }
    if ($section === 'announcements') {
        if (!hv5_table_exists('owner_announcements')) json_ok([]);
        json_ok(db()->query('SELECT id, title, body, published_at FROM owner_announcements ORDER BY published_at DESC LIMIT 20')->fetchAll());
    }
    if ($section === 'support') {
        require_permission('owner.support');
        if (!hv5_table_exists('owner_support_tickets')) json_ok([]);
        $stmt = db()->prepare('SELECT * FROM owner_support_tickets WHERE user_id=? ORDER BY created_at DESC');
        $stmt->execute([$user['id']]);
        json_ok($stmt->fetchAll());
    }
    json_error('Unknown section', 404);
}

csrf_check();

if ($method === 'POST') {
    if ($section === 'support') {
        require_permission('owner.support');
        $err = v_required($d, ['subject']);
        if ($err) json_error('Validation failed', 422, $err);
        db()->prepare('INSERT INTO owner_support_tickets (user_id, property_id, subject, body) VALUES (?,?,?,?)')
            ->execute([(int)$user['id'], !empty($d['property_id']) ? (int)$d['property_id'] : null, v_str($d, 'subject', 190), (string)($d['body'] ?? '')]);
        $tid = (int)db()->lastInsertId();
        if (function_exists('hv4_emit_event')) hv4_emit_event('owner.support.created', ['id' => $tid], 'support', $tid);
        json_ok(['id' => $tid], 'Support ticket created');
    }
    if ($section === 'announcements' && has_permission('settings.manage')) {
        db()->prepare('INSERT INTO owner_announcements (title, body, created_by) VALUES (?,?,?)')
            ->execute([v_str($d, 'title', 190), (string)($d['body'] ?? ''), $user['id']]);
        json_ok(['id' => (int)db()->lastInsertId()], 'Published');
    }
}

json_error('Method not allowed', 405);
