<?php
require_auth();
require_permission('finance.advanced');
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$pdo = db();

if ($method === 'GET') {
    $properties = $pdo->query('SELECT id, name, currency, base_price FROM properties WHERE deleted_at IS NULL')->fetchAll();
    $analytics = [];
    foreach ($properties as $p) {
        $pid = (int)$p['id'];
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(total),0) FROM bookings WHERE property_id=? AND status NOT IN ('cancelled','no_show') AND check_in >= DATE_FORMAT(CURDATE(),'%Y-%m-01')");
        $stmt->execute([$pid]);
        $rev = (float)$stmt->fetchColumn();
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM expenses WHERE property_id=? AND expense_date >= DATE_FORMAT(CURDATE(),'%Y-%m-01')");
        $stmt->execute([$pid]);
        $exp = (float)$stmt->fetchColumn();
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(nights),0) FROM bookings WHERE property_id=? AND status NOT IN ('cancelled','no_show') AND check_in >= DATE_FORMAT(CURDATE(),'%Y-%m-01')");
        $stmt->execute([$pid]);
        $nights = (int)$stmt->fetchColumn();
        $daysInMonth = (int)date('t');
        $adr = $nights > 0 ? round($rev / $nights, 2) : 0;
        $occ = $daysInMonth > 0 ? round(($nights / $daysInMonth) * 100, 1) : 0;
        $revpar = round($rev / max(1, $daysInMonth), 2);
        $analytics[] = [
            'property_id' => $pid,
            'name' => $p['name'],
            'revenue_mtd' => $rev,
            'expenses_mtd' => $exp,
            'profit_mtd' => $rev - $exp,
            'adr' => $adr,
            'occupancy_pct' => $occ,
            'revpar' => $revpar,
        ];
    }
    $statements = [];
    if (hv4_table_exists('owner_statements')) {
        $statements = $pdo->query('SELECT os.*, p.name AS property_name FROM owner_statements os JOIN properties p ON p.id=os.property_id ORDER BY os.period_start DESC LIMIT 20')->fetchAll();
    }
    json_ok(['analytics' => $analytics, 'statements' => $statements]);
}

csrf_check();

if ($method === 'POST' && hv4_table_exists('owner_statements')) {
    $err = v_required($d, ['property_id', 'period_start', 'period_end']);
    if ($err) json_error('Validation failed', 422, $err);
    $pid = (int)$d['property_id'];
    $ps = v_date($d['period_start'], 'period_start');
    $pe = v_date($d['period_end'], 'period_end');
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(total),0) FROM bookings WHERE property_id=? AND status NOT IN ('cancelled','no_show') AND check_in BETWEEN ? AND ?");
    $stmt->execute([$pid, $ps, $pe]);
    $gross = (float)$stmt->fetchColumn();
    $stmt = $pdo->prepare('SELECT COALESCE(SUM(amount),0) FROM expenses WHERE property_id=? AND expense_date BETWEEN ? AND ?');
    $stmt->execute([$pid, $ps, $pe]);
    $exp = (float)$stmt->fetchColumn();
    $commission = (float)($d['commission'] ?? round($gross * 0.15, 2));
    $net = $gross - $exp - $commission;
    $pdo->prepare('INSERT INTO owner_statements (property_id, period_start, period_end, gross_revenue, expenses, commission, net_payout, status) VALUES (?,?,?,?,?,?,?,?)')
        ->execute([$pid, $ps, $pe, $gross, $exp, $commission, $net, 'draft']);
    json_ok(['id' => (int)$pdo->lastInsertId(), 'net_payout' => $net], 'Statement created');
}

json_error('Method not allowed', 405);
