<?php
// Reports & Recommendations — with admin approval flow
require_auth();
$u = current_user();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$id = (int)($d['id'] ?? 0);

if ($method === 'GET') {
    require_permission('reports.view');
    if ($id) {
        $s = db()->prepare('SELECT r.*, u.name AS author_name, u.email AS author_email, u.phone AS author_phone, a.name AS approved_by_name FROM staff_reports r JOIN users u ON u.id = r.created_by LEFT JOIN users a ON a.id = r.approved_by WHERE r.id = ?');
        $s->execute([$id]);
        $row = $s->fetch();
        if (!$row) json_error('Not found', 404);
        json_ok($row);
    }
    $where = '1=1'; $params = [];
    if (!empty($d['status'])) { $where .= ' AND r.status = ?'; $params[] = $d['status']; }
    if (!empty($d['type']))   { $where .= ' AND r.type = ?';   $params[] = $d['type']; }
    $s = db()->prepare("SELECT r.*, u.name AS author_name, a.name AS approved_by_name FROM staff_reports r JOIN users u ON u.id = r.created_by LEFT JOIN users a ON a.id = r.approved_by WHERE $where ORDER BY r.created_at DESC LIMIT 200");
    $s->execute($params);
    json_ok($s->fetchAll());
}

csrf_check();

if ($method === 'POST') {
    require_permission('reports.view'); // anyone who can view can submit
    $err = v_required($d, ['title', 'body']);
    if ($err) json_error('Validation failed', 422, $err);

    $type   = v_enum($d['type'] ?? 'report', ['report','recommendation','complaint','suggestion'], 'type', 'report');
    $urgent = !empty($d['urgent']) ? 1 : 0;

    $db = db();
    $db->prepare("INSERT INTO staff_reports (created_by, title, body, type, urgent, status, created_at, updated_at) VALUES (?,?,?,?,?,'pending',NOW(),NOW())")
       ->execute([$u['id'], v_str($d,'title',190), trim((string)$d['body']), $type, $urgent]);
    $nid = (int)$db->lastInsertId();

    // Notify all admins + super_admins
    $urgentTag = $urgent ? '🚨 URGENT — ' : '';
    hv4_notify_admins(
        "{$urgentTag}New {$type}: " . mb_strimwidth(v_str($d,'title',190), 0, 80, '…'),
        "From {$u['name']}: " . mb_strimwidth(trim((string)$d['body']), 0, 120, '…'),
        'report',
        '../pages/reports.html'
    );
    hv4_emit_event('report.submitted', ['id' => $nid, 'type' => $type, 'urgent' => $urgent], 'report', $nid);
    audit('report.create', 'report', $nid);
    json_ok(['id' => $nid], 'Submitted and admin notified.');
}

if ($method === 'PUT') {
    if (!$id) json_error('id required', 422);
    $action = $d['action'] ?? '';

    // Approve / Reject — admin only
    if (in_array($action, ['approve','reject'], true)) {
        require_permission('settings.manage');
        $status   = $action === 'approve' ? 'approved' : 'rejected';
        $feedback = trim((string)($d['feedback'] ?? ''));
        db()->prepare("UPDATE staff_reports SET status=?, approved_by=?, admin_feedback=?, actioned_at=NOW(), updated_at=NOW() WHERE id=?")
           ->execute([$status, $u['id'], $feedback, $id]);

        // Notify the report author
        $row = db()->prepare('SELECT r.title, r.created_by, r.type, u.name AS author_name FROM staff_reports r JOIN users u ON u.id=r.created_by WHERE r.id=?');
        $row->execute([$id]);
        $rep = $row->fetch();
        if ($rep) {
            $icon = $status === 'approved' ? '✅' : '❌';
            hv4_notify_user((int)$rep['created_by'],
                "{$icon} Your {$rep['type']} was {$status}",
                $feedback ?: "Admin has {$status} your submission: \"{$rep['title']}\"",
                'report', '../pages/reports.html'
            );
        }
        hv4_emit_event('report.'.$status, ['id' => $id], 'report', $id);
        audit('report.'.$status, 'report', $id);
        json_ok([], ucfirst($status));
    }

    // Edit own report (only if still pending)
    require_permission('reports.view');
    $row = db()->prepare('SELECT id, created_by, status FROM staff_reports WHERE id=?');
    $row->execute([$id]);
    $rep = $row->fetch();
    if (!$rep) json_error('Not found', 404);
    if ((int)$rep['created_by'] !== (int)$u['id'] && !can('settings.manage')) json_error('Forbidden', 403);
    if ($rep['status'] !== 'pending' && !can('settings.manage')) json_error('Cannot edit a report that has already been actioned', 403);

    $fields = []; $vals = [];
    foreach (['title','body','type','urgent'] as $f) {
        if (array_key_exists($f, $d)) { $fields[] = "$f=?"; $vals[] = $d[$f]; }
    }
    if (!$fields) json_error('Nothing to update', 422);
    $vals[] = $id;
    db()->prepare('UPDATE staff_reports SET ' . implode(',', $fields) . ', updated_at=NOW() WHERE id=?')->execute($vals);
    json_ok([], 'Updated');
}

if ($method === 'DELETE') {
    require_permission('settings.manage');
    if (!$id) json_error('id required', 422);
    db()->prepare('DELETE FROM staff_reports WHERE id=?')->execute([$id]);
    json_ok([], 'Deleted');
}

json_error('Method not allowed', 405);
