<?php

namespace App\Http\Controllers\Api\Package;

use App\Http\Controllers\Controller;
use App\Http\Requests\Package\StorePackageRequest;
use App\Http\Requests\Package\UpdatePackageRequest;
use App\Http\Resources\PackageResource;
use App\Models\JobPackage;
use App\Services\Package\PackageService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class PackageController extends Controller
{
    protected PackageService $packageService;

    public function __construct(PackageService $packageService)
    {
        $this->packageService = $packageService;
    }

    /**
     * Display a listing of packages
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        $filters = $request->only(['status', 'job_type', 'province', 'regency', 'min_budget', 'max_budget', 'search']);
        $packages = $this->packageService->getAll($filters);
        return PackageResource::collection($packages);
    }

    /**
     * Store a newly created package
     */
    public function store(StorePackageRequest $request): JsonResponse
    {
        $package = $this->packageService->create($request->validated());

        return response()->json([
            'success' => true,
            'message' => 'Paket pekerjaan berhasil dibuat',
            'data' => new PackageResource($package),
        ], 201);
    }

    /**
     * Display the specified package
     */
    public function show(JobPackage $package): PackageResource
    {
        return new PackageResource($package->load(['ppk', 'documents']));
    }

    /**
     * Update the specified package
     */
    public function update(UpdatePackageRequest $request, JobPackage $package): JsonResponse
    {
        $updated = $this->packageService->update($package, $request->validated());

        return response()->json([
            'success' => true,
            'message' => 'Paket pekerjaan berhasil diperbarui',
            'data' => new PackageResource($updated),
        ]);
    }

    /**
     * Remove the specified package
     */
    public function destroy(JobPackage $package): JsonResponse
    {
        $this->packageService->delete($package);

        return response()->json([
            'success' => true,
            'message' => 'Paket pekerjaan berhasil dihapus',
        ]);
    }

    /**
     * Activate package (draft → active)
     */
    public function activate(JobPackage $package): JsonResponse
    {
        $activated = $this->packageService->activate($package);

        return response()->json([
            'success' => true,
            'message' => 'Paket berhasil diaktifkan',
            'data' => new PackageResource($activated),
        ]);
    }

    /**
     * 👇 INI YANG DITAMBAH! Upload document to package
     */
    public function uploadDocument(Request $request, JobPackage $package): JsonResponse
    {
        $request->validate([
            'document' => 'required|file|max:10240|mimes:pdf,doc,docx,xls,xlsx,jpg,jpeg,png',
        ]);

        $document = $this->packageService->uploadDocument($package, $request->file('document'));

        return response()->json([
            'success' => true,
            'message' => 'Dokumen berhasil diupload',
            'data' => [
                'id' => $document->id,
                'name' => $document->name,
                'file_url' => $document->file_url,
                'size' => $document->size,
                'type' => $document->type,
                'uploaded_at' => $document->created_at->format('d/m/Y H:i'),
            ],
        ]);
    }

    /**
     * Submit package for matching
     */
    public function submit(JobPackage $package): JsonResponse
    {
        $submitted = $this->packageService->submit($package);

        return response()->json([
            'success' => true,
            'message' => 'Paket berhasil disubmit untuk matching',
            'data' => new PackageResource($submitted),
        ]);
    }

    /**
     * Cancel package
     */
    public function cancel(Request $request, JobPackage $package): JsonResponse
    {
        $reason = $request->input('reason');
        $cancelled = $this->packageService->cancel($package, $reason);

        return response()->json([
            'success' => true,
            'message' => 'Paket berhasil dibatalkan',
            'data' => new PackageResource($cancelled),
        ]);
    }

    /**
     * Get PPK's own packages
     */
    public function ppkPackages(Request $request): AnonymousResourceCollection
    {
        $filters = $request->only(['status', 'search']);
        $packages = $this->packageService->getPpkPackages(auth()->id(), $filters);
        return PackageResource::collection($packages);
    }

    /**
     * Get matching queue (for agent)
     */
    public function matchingQueue(): JsonResponse
    {
        $packages = $this->packageService->getMatchingQueue();

        return response()->json([
            'success' => true,
            'data' => PackageResource::collection($packages),
            'total' => $packages->count(),
        ]);
    }

    /**
     * Get package statistics
     */
    public function statistics(Request $request): JsonResponse
    {
        $ppkId = $request->input('ppk_id');
        $stats = $this->packageService->getStatistics($ppkId);

        return response()->json([
            'success' => true,
            'data' => $stats,
        ]);
    }
}