<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Services\ReportService;
use App\Traits\DeleteModelTrait;
use App\Traits\FlashMessageTrait;
use App\Models\Report;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminReportController extends Controller
{
    use DeleteModelTrait, FlashMessageTrait;

    protected $reportService;

    public function __construct(ReportService $reportService)
    {
        $this->reportService = $reportService;
    }

    public function index(Request $request)
    {
        try {
            $perPage = 5;
            $reports = Report::with(['reporter'])
                ->orderBy('created_at', 'desc')
                ->paginate($perPage);
            
            $reports->getCollection()->transform(function ($report, $index) use ($reports) {
                $report->sn = ($reports->currentPage() - 1) * $reports->perPage() + $index + 1;
                $report->reporter_name = $report->reporter->name ?? 'N/A';
                $report->status_text = match($report->status) {
                    1 => 'pending',
                    2 => 'reviewed',
                    3 => 'resolved',
                    default => 'unknown'
                };
                return $report;
            });

            return Inertia::render('Admin/Reports/Report', [
                'reports' => $reports->items(),
                'pagination' => [
                    'current_page' => $reports->currentPage(),
                    'last_page' => $reports->lastPage(),
                    'per_page' => $reports->perPage(),
                    'total' => $reports->total(),
                    'from' => $reports->firstItem(),
                    'to' => $reports->lastItem(),
                    'links' => $reports->linkCollection()->toArray(),
                ]
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load reports: ' . $e->getMessage());
        }
    }

    public function show($id)
    {
        try {
            $report = Report::with(['reporter'])->find($id);
            
            if (!$report) {
                return response()->json(['error' => 'Report not found'], 404);
            }

            return response()->json($report);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function updateStatus(Request $request, $id)
    {
        try {
            $request->validate(['status' => 'required|in:1,2,3']);
            
            $report = Report::findOrFail($id);
            $report->update(['status' => $request->status]);
            
            return $this->success('Report status updated successfully');
        } catch (\Exception $e) {
            return $this->error('Failed to update report status: ' . $e->getMessage());
        }
    }

    public function destroy($id)
    {
        try {
            $report = Report::find($id);

            if (!$report) {
                return $this->error('Report not found');
            }

            return $this->deleteModel($id, new Report());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * Display pending reports
     */
    public function pendingReports(Request $request)
    {
        try {
            $perPage = $request->input('per_page', 15);
            $result = $this->reportService->getPendingReports($perPage);
            
            // Format data for display
            $startSN = (($result['pagination']['current_page'] - 1) * $result['pagination']['per_page']) + 1;
            
            $formattedReports = array_map(function ($report, $index) use ($startSN) {
                $reportData = is_array($report) ? $report : $report->toArray();
                return [
                    'id' => $reportData['id'] ?? $report->id ?? null,
                    'sn' => $startSN + $index,
                    'reporter_name' => $reportData['reporter']['name'] ?? $report->reporter->name ?? 'N/A',
                    'reported_item_type' => $reportData['reported_item_type'] ?? $report->reported_item_type ?? 'N/A',
                    'reason' => $reportData['reason'] ?? $report->reason ?? 'N/A',
                    'description' => $reportData['description'] ?? $report->description ?? 'N/A',
                    'status' => 'pending',
                    'status_badge' => 'warning',
                    'created_at' => isset($reportData['created_at']) 
                        ? date('Y-m-d', strtotime($reportData['created_at'])) 
                        : (isset($report->created_at) ? $report->created_at->format('Y-m-d') : 'N/A'),
                ];
            }, $result['data'], array_keys($result['data']));

            return Inertia::render('Admin/Reports/PendingReports', [
                'reports' => $formattedReports,
                'pagination' => $result['pagination'],
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load pending reports: ' . $e->getMessage());
        }
    }

    /**
     * Display report statistics
     */
    public function statistics()
    {
        try {
            $stats = $this->reportService->getReportStatistics();
            
            return Inertia::render('Admin/Reports/ReportStatistics', [
                'statistics' => $stats,
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load statistics: ' . $e->getMessage());
        }
    }
}
