<?php
class RecycleBinController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('recycle-bin/index', [
            'title' => lang('admin.recycle_bin'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/recycle-bin'], ['label' => lang('admin.recycle_bin')]],
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw = (int)$request->post('draw', 1);
        $start = (int)$request->post('start', 0);
        $length = (int)$request->post('length', 25);
        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM recycle_bin WHERE restored = 0 AND permanently_deleted = 0");
        $rows = $db->fetchAll(
            "SELECT rb.*, u.full_name_en as deleted_by_name FROM recycle_bin rb LEFT JOIN auth_users u ON rb.deleted_by = u.id WHERE rb.restored = 0 AND rb.permanently_deleted = 0 ORDER BY rb.deleted_at DESC LIMIT {$length} OFFSET {$start}"
        );
        $data = [];
        foreach ($rows as $r) {
            $actions = '<div class="btn-group btn-group-sm">';
            $actions .= '<button class="btn btn-outline-success btn-restore" data-id="' . $r['id'] . '" title="Restore"><i class="fas fa-undo"></i></button>';
            $actions .= '<button class="btn btn-outline-danger btn-purge" data-id="' . $r['id'] . '" title="Permanently Delete"><i class="fas fa-trash-alt"></i></button>';
            $actions .= '</div>';
            $data[] = [
                'type' => e($r['entity_type']),
                'entity_id' => $r['entity_id'],
                'deleted_by' => e($r['deleted_by_name'] ?? '-'),
                'deleted_at' => format_datetime($r['deleted_at']),
                'deadline' => $r['restore_deadline'] ? format_datetime($r['restore_deadline']) : '-',
                'actions' => $actions,
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $total, 'data' => $data]);
    }

    public function restore(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $db = $this->db();
        $item = $db->fetchOne("SELECT * FROM recycle_bin WHERE id = ? AND restored = 0 AND permanently_deleted = 0", [$id]);
        if (!$item) { $this->json(['success' => false, 'message' => 'Item not found'], 404); return; }

        $entityData = json_decode($item['entity_data'], true);
        if ($entityData && !empty($item['entity_type'])) {
            try {
                $db->update($item['entity_type'], ['is_deleted' => 0, 'deleted_at' => null, 'deleted_by' => null], 'id = ?', [$item['entity_id']]);
            } catch (\Exception $e) {
                Logger::warning('Could not restore entity directly: ' . $e->getMessage());
            }
        }

        $db->update('recycle_bin', ['restored' => 1, 'restored_by' => Auth::id(), 'restored_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        $this->audit('update', 'recycle_bin', $id, 'Restored entity: ' . $item['entity_type'] . '#' . $item['entity_id']);
        $this->json(['success' => true, 'message' => 'Item restored']);
    }

    public function purge(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $this->db()->update('recycle_bin', ['permanently_deleted' => 1, 'permanently_deleted_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        $this->audit('delete', 'recycle_bin', $id, 'Permanently deleted recycled item');
        $this->json(['success' => true, 'message' => 'Item permanently deleted']);
    }
}