<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\LabReport;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LabReportController extends Controller
{
    /**
     * GET /lab-reports
     * Public list of all active lab reports with product info.
     */
    public function index(Request $request): JsonResponse
    {
        $query = LabReport::with(['product.primaryImage'])
            ->where('is_active', true)
            ->whereHas('product', fn($q) => $q->where('status', 'active'));

        if ($request->filled('search')) {
            $s = $request->search;
            $query->where(function ($q) use ($s) {
                $q->where('batch_number', 'like', "%{$s}%")
                  ->orWhere('lab_name', 'like', "%{$s}%")
                  ->orWhereHas('product', fn($pq) => $pq->where('name', 'like', "%{$s}%"));
            });
        }

        if ($request->filled('test_type')) {
            $query->where('test_type', $request->test_type);
        }

        $reports = $query->orderBy('test_date', 'desc')->get()->map(fn($r) => [
            'id'                 => $r->id,
            'product_id'         => $r->product_id,
            'product_name'       => $r->product?->name,
            'product_slug'       => $r->product?->slug,
            'product_image'      => $r->product?->primaryImage?->url,
            'batch_number'       => $r->batch_number,
            'test_date'          => $r->test_date,
            'lab_name'           => $r->lab_name,
            'test_type'          => $r->test_type,
            'purity_percentage'  => $r->purity_percentage,
            'pdf_url'            => $r->pdf_url,
            'certificate_number' => $r->certificate_number,
        ]);

        return response()->json(['data' => $reports]);
    }

    // ── Admin ──────────────────────────────────────────────────────────────────

    /**
     * GET /admin/lab-reports
     */
    public function adminIndex(): JsonResponse
    {
        $reports = LabReport::with('product')
            ->orderBy('test_date', 'desc')
            ->get()
            ->map(fn($r) => [
                'id'                 => $r->id,
                'product_id'         => $r->product_id,
                'product_name'       => $r->product?->name,
                'batch_number'       => $r->batch_number,
                'test_date'          => $r->test_date,
                'lab_name'           => $r->lab_name,
                'test_type'          => $r->test_type,
                'purity_percentage'  => $r->purity_percentage,
                'pdf_url'            => $r->pdf_url,
                'certificate_number' => $r->certificate_number,
                'is_active'          => $r->is_active,
            ]);

        return response()->json(['data' => $reports]);
    }

    /**
     * POST /admin/lab-reports
     */
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'product_id'         => 'required|integer|exists:products,id',
            'batch_number'       => 'required|string|max:100',
            'test_date'          => 'required|date',
            'lab_name'           => 'required|string|max:255',
            'test_type'          => 'required|in:HPLC,mass_spec,both',
            'purity_percentage'  => 'required|numeric|min:0|max:100',
            'pdf_url'            => 'required|url',
            'certificate_number' => 'nullable|string|max:100',
            'is_active'          => 'boolean',
        ]);

        $report = LabReport::create($data);

        return response()->json(['data' => $report->load('product')], 201);
    }

    /**
     * PUT /admin/lab-reports/{id}
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $report = LabReport::findOrFail($id);

        $data = $request->validate([
            'product_id'         => 'sometimes|integer|exists:products,id',
            'batch_number'       => 'sometimes|string|max:100',
            'test_date'          => 'sometimes|date',
            'lab_name'           => 'sometimes|string|max:255',
            'test_type'          => 'sometimes|in:HPLC,mass_spec,both',
            'purity_percentage'  => 'sometimes|numeric|min:0|max:100',
            'pdf_url'            => 'sometimes|url',
            'certificate_number' => 'nullable|string|max:100',
            'is_active'          => 'sometimes|boolean',
        ]);

        $report->update($data);

        return response()->json(['data' => $report->load('product')]);
    }

    /**
     * DELETE /admin/lab-reports/{id}
     */
    public function destroy(int $id): JsonResponse
    {
        LabReport::findOrFail($id)->delete();
        return response()->json(['message' => 'Lab report deleted.']);
    }
}
