<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AdReport;
use App\Models\Service;
use App\Models\ServiceRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ServiceRequestController extends Controller
{
    protected $FrontendController;
    public function __construct(FrontendController $FrontendController)
    {
        $this->FrontendController = $FrontendController;
    }
    public function store(Request $request)
    {
        $validated = $request->validate([
            'request_id' => 'required|string',
            'service_id' => 'required|integer',
            'service_request_type_id' => 'required|integer',
            'number' => 'nullable|string|max:50',
        ]);

        // Get existing record (NOT ->exists())
        $existing = ServiceRequest::where('request_id', $validated['request_id'])
            ->where('service_id', $validated['service_id'])
            ->first();

        $serviceModel = Service::where('id', $validated['service_id'])->first();
        if (!$serviceModel) {
            return response()->json(['message' => 'Service not found'], 404);
        }

        $userId = $serviceModel->user_id;   // ← GET USER ID
        if ($existing) {

            // CASE 1: Same service_request_type_id → return same record
            if ($existing->service_request_type_id == $validated['service_request_type_id']) {
                sendRequestNotification('FindFlicker', 'Contact Changed notification from FindFlicker', "history_update", [$userId]);
                return response()->json([
                    'status' => true,
                    'message' => 'Service request already exists.',
                    'data' => $existing
                ]);
            }

            // CASE 2: Different → UPDATE existing
            $existing->update([
                'service_request_type_id' => $validated['service_request_type_id'],
                'number' => $validated['number'],
            ]);
            sendRequestNotification('FindFlicker', 'Contact Changed notification from FindFlicker', "history_update", [$userId]);


            return response()->json([
                'status' => true,
                'message' => 'Service request updated successfully.',
                'data' => $existing
            ]);
        }

        // CASE 3: No record → CREATE
        $data = ServiceRequest::create($validated);
        sendRequestNotification('FindFlicker', 'Contact notification from FindFlicker', "history_update");

        return response()->json([
            'status' => true,
            'message' => 'Service request created',
            'data' => $data
        ]);
    }


    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'service_id' => 'sometimes|integer',
            'service_request_type_id' => 'sometimes|integer',
            'number' => 'sometimes|string|max:50',
        ]);

        $data = ServiceRequest::findOrFail($id);
        $data->update($validated);

        return response()->json([
            'status' => true,
            'message' => 'Service request updated',
            'data' => $data
        ]);
    }
    public function serviceRequestStore(Request $request)
    {


        $request->validate([
            'serviceId' => 'required|integer',
            'email' => 'required|email',
            'message' => 'required|string',
            'proofs.*' => 'nullable|image|max:2048', // Max 2MB per image
        ]);

        $imagePaths = [];

        if ($request->hasFile('proofs')) {

            foreach ($request->file('proofs') as $file) {

                // Create folder if not exists
                $folderPath = public_path('uploads/reports/');
                if (!file_exists($folderPath)) {
                    mkdir($folderPath, 0777, true);
                }

                // Create unique file name
                $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();

                // Move file to /public/uploads/reports/
                $file->move($folderPath, $filename);

                // Save relative path to database
                $imagePaths[] =   $folderPath . $filename;
            }
        }


        $report = AdReport::create([
            'service_id' => $request->serviceId,
            'email' => $request->email,
            'message' => $request->message,
            'images' => $imagePaths, // stored as JSON automatically
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Report submitted successfully',
            'report' => $report
        ]);
    }
    // public function searchDistanceIncreaseRequest(Request $request)
    // {

    //     $request_id = $request->requestId;
    //     $distance = $request->distance;
    //     $getServicesUserIds = $this->FrontendController->getrequestBasedServices($request_id, $distance);

    //     if ($getServicesUserIds) {
    //          sendRequestNotification('FindFlicker', 'New-request notification from FindFlicker', $getServicesUserIds);
    //     }
    //     // Return JSON response
    //     return response()->json([
    //         'status'  => true,
    //         'message' => 'Distance increased search executed successfully',
    //         'request_id' => $request_id,
    //         'distance'   => $distance,
    //         'users_found' => $getServicesUserIds ?? [],
    //     ], 200);
    // }
    public function searchDistanceIncreaseRequest(Request $request)
    {
        try {

            $request_id = $request->requestId;
            $distance   = $request->distance;

            $getServicesUserIds = $this->FrontendController
                ->getrequestBasedServices($request_id, $distance);

            if ($getServicesUserIds) {
                sendRequestNotification(
                    'FindFlicker',
                    'New-request notification from FindFlicker',
                    "history_update",
                    $getServicesUserIds
                );
            }

            return response()->json([
                'status'      => true,
                'message'     => 'Distance increased search executed successfully',
                'request_id'  => $request_id,
                'distance'    => $distance,
                'users_found' => $getServicesUserIds ?? [],
            ], 200);
        } catch (\Exception $e) {

            // Log error
            Log::error("searchDistanceIncreaseRequest error: " . $e->getMessage(), [
                'request_id' => $request->requestId,
                'distance'   => $request->distance
            ]);

            return response()->json([
                'status'  => false,
                'message' => 'Something went wrong while increasing distance search.',
                'error'   => $e->getMessage(),
            ], 500);
        }
    }
}
