<?php

namespace App\Modules\Services\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ServiceRequest;
use Illuminate\Support\Facades\Auth;
use OpenApi\Attributes as OA;

class ServiceProviderController extends Controller
{
    #[OA\Post(
        path: '/api/vendor/availability',
        operationId: 'vendorAvailability',
        summary: 'Toggle Availability',
        description: 'Allows a service provider to toggle their online status.',
        security: [['passport' => []]],
        tags: ['Vendor', 'Services'],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                required: ['is_online'],
                properties: [
                    new OA\Property(property: 'is_online', type: 'boolean', example: true)
                ]
            )
        ),
        responses: [
            new OA\Response(response: 200, description: 'Availability updated successfully'),
            new OA\Response(response: 403, description: 'Unauthorized or invalid vendor type')
        ]
    )]
    public function toggleAvailability(Request $request)
    {
        $vendor = Auth::user()->vendor;
        
        if (!$vendor || $vendor->vendorType?->slug !== 'service_provider') {
            return response()->json(['message' => 'Unauthorized or invalid vendor type'], 403);
        }

        $request->validate([
            'is_online' => 'required|boolean'
        ]);

        $vendor->update(['is_online' => $request->is_online]);

        return response()->json([
            'message' => 'Availability updated successfully',
            'is_online' => $vendor->is_online
        ]);
    }

    #[OA\Get(
        path: '/api/vendor/service-provider/dashboard',
        operationId: 'serviceProviderDashboard',
        summary: 'Service Provider Dashboard',
        description: 'Fetches stats, pending jobs, and active jobs for the service provider.',
        security: [['passport' => []]],
        tags: ['Vendor', 'Services'],
        responses: [
            new OA\Response(response: 200, description: 'Dashboard data retrieved successfully'),
            new OA\Response(response: 403, description: 'Unauthorized or invalid vendor type')
        ]
    )]
    public function dashboard(Request $request)
    {
        $vendor = Auth::user()->vendor;

        if (!$vendor || $vendor->vendorType?->slug !== 'service_provider') {
            return response()->json(['message' => 'Unauthorized or invalid vendor type'], 403);
        }

        $pendingJobs = ServiceRequest::with(['customer', 'providerService'])
            ->where('vendor_id', $vendor->id)
            ->where('status', 'pending')
            ->latest()
            ->get();
            
        $activeJobs = ServiceRequest::with(['customer', 'providerService'])
            ->where('vendor_id', $vendor->id)
            ->whereIn('status', ['accepted', 'ongoing'])
            ->latest()
            ->get();

        $stats = [
            'total_completed' => ServiceRequest::where('vendor_id', $vendor->id)->where('status', 'completed')->count(),
            'total_earnings' => $vendor->wallet ? $vendor->wallet->balance : 0,
            'is_online' => $vendor->is_online
        ];

        return response()->json([
            'stats' => $stats,
            'pending_jobs' => $pendingJobs,
            'active_jobs' => $activeJobs
        ]);
    }

    #[OA\Post(
        path: '/api/vendor/service-provider/jobs/{id}/status',
        operationId: 'updateServiceProviderJobStatus',
        summary: 'Update Job Status',
        description: 'Updates the status of a specific service request.',
        security: [['passport' => []]],
        tags: ['Vendor', 'Services'],
        parameters: [
            new OA\Parameter(name: 'id', in: 'path', required: true, description: 'Job ID', schema: new OA\Schema(type: 'integer'))
        ],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                required: ['status'],
                properties: [
                    new OA\Property(property: 'status', type: 'string', enum: ['accepted', 'ongoing', 'completed', 'cancelled'], example: 'accepted')
                ]
            )
        ),
        responses: [
            new OA\Response(response: 200, description: 'Job status updated'),
            new OA\Response(response: 404, description: 'Job not found')
        ]
    )]
    public function updateJobStatus(Request $request, $id)
    {
        $vendor = Auth::user()->vendor;
        $job = ServiceRequest::where('vendor_id', $vendor->id)->findOrFail($id);

        $request->validate([
            'status' => 'required|in:accepted,ongoing,completed,cancelled'
        ]);

        $job->update(['status' => $request->status]);
        
        // TODO: If completed, handle commissions and payouts

        return response()->json([
            'message' => 'Job status updated',
            'job' => $job->load('providerService')
        ]);
    }
}
