<?php

namespace App\Services\DrinageWater;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use App\Models\DrinageWater\PortableWater;
use App\Models\ServiceCredential;
use App\Services\CurlAPiService;
use App\Services\AapaleSarkarLoginCheckService;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;
use App\Models\Status;
use App\Services\CommonService;

class PortableWaterService
{
    protected $curlAPiService;
    protected $aapaleSarkarLoginCheckService;
    protected $commonservice;

    public function __construct(CurlAPiService $curlAPiService, AapaleSarkarLoginCheckService $aapaleSarkarLoginCheckService , CommonService $commonservice)
    {
        $this->curlAPiService = $curlAPiService;
        $this->aapaleSarkarLoginCheckService = $aapaleSarkarLoginCheckService;
        $this->commonservice = $commonservice;
    }

//    public function store_old($request)
// {
//     DB::beginTransaction();

//     try {
//         $request['user_id'] = Auth::user()->id;
//         $request['service_id'] = "8924";

//         // Save application document
//         if ($request->hasFile('application_documents')) {
//             $path = $request->file('application_documents')->store('PortableWater/water-quality', 'public');
//             $request['application_document'] = $path;
//         }

//         // Save uploaded application (prescribed format)
//         if ($request->hasFile('uploaded_applications')) {
//             $path2 = $request->file('uploaded_applications')->store('PortableWater/water-quality', 'public');
//             $request['uploaded_applications'] = $path2;
//         }

//         // Create record
//         $waterQualityComplaint = PortableWater::create($request->except('application_no'));

//         if ($waterQualityComplaint) {
//             $applicationNo = 'MBMC/' . $request['service_id'] . '/' . $waterQualityComplaint->id . '/' . date('dmY');
//             $waterQualityComplaint->application_no = $applicationNo;
//             $waterQualityComplaint->save();

//             $status = Status::create([
//                 'service_id' => 8924,
//                 'department_id' => 12,
//                 'table_id' => $waterQualityComplaint->id,
//                 'user_id' => Auth::user()->id
//             ]);

//             $this->commonservice->store_approval_hierarchies($waterQualityComplaint, Auth::user(), $status);
//         }

//         DB::commit();
//         return [true];
//     } catch (\Exception $e) {
//         DB::rollback();
//         Log::error('Error in store method: ' . $e->getMessage());
//         return [false, $e->getMessage()];
//     }
// }


public function store($request)
{
    DB::beginTransaction();

    try {
        // ✅ Copy all inputs to a data array
        $data = $request->all();

        // ✅ Add extra fields
        $data['user_id'] = Auth::user()->id;
        $data['service_id'] = 8924;

        // ✅ Handle file: application_documents
        if ($request->hasFile('application_documents')) {
            $file = $request->file('application_documents');
            $path = $file->store('PortableWater/water-quality', 'public');
            $data['application_document'] = $path;
        }

        // ✅ Handle file: uploaded_applications
        if ($request->hasFile('uploaded_applications')) {
            $file = $request->file('uploaded_applications');
            $path = $file->store('PortableWater/water-quality', 'public');
            $data['uploaded_applications'] = $path;
        }

        // ✅ Create record
        $waterQualityComplaint = PortableWater::create($data);

        // ✅ Generate Application Number
        if ($waterQualityComplaint) {
            $applicationNo = 'MBMC/' . $data['service_id'] . '/' . $waterQualityComplaint->id . '/' . date('dmY');
            $waterQualityComplaint->application_no = $applicationNo;
            $waterQualityComplaint->save();

            // ✅ Insert into Status Table
            $status = Status::create([
                'service_id' => 8924,
                'department_id' => 12,
                'table_id' => $waterQualityComplaint->id,
                'user_id' => Auth::user()->id,
            ]);

            $this->commonservice->store_approval_hierarchies($waterQualityComplaint, Auth::user(), $status);
        }

        DB::commit();
        return [true];
    } catch (\Exception $e) {
        DB::rollback();
        Log::error('Error in store method: ' . $e->getMessage());
        return [false, $e->getMessage()];
    }
}




   


    public function edit($id)
    {
        return PortableWater::find($id);
    }

    public function update($request, $id)
    {
        DB::beginTransaction();
        try {
            // Find the existing record
            $waterQualityComplaint = PortableWater::findOrFail($id);
            // Handle file uploads and update original file names
            if ($request->hasFile('application_documents')) {
                if ($waterQualityComplaint && Storage::exists($waterQualityComplaint->application_document)) {
                    Storage::delete($waterQualityComplaint->application_document);
                }
                $request['application_document'] = $request->application_documents->store('water-department/water-quality');
            }


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

    // Delete old file if it exists
    if ($waterQualityComplaint && Storage::disk('public')->exists($waterQualityComplaint->uploaded_applications)) {
        Storage::disk('public')->delete($waterQualityComplaint->uploaded_applications);
    }

    // Store new file in the same folder and disk
    $request['uploaded_applications'] = $request->uploaded_applications->store('PortableWater/water-quality', 'public');
}
            $waterQualityComplaint->update($request->all());



            // code to send data to department
            if ($request->hasFile('application_documents')) {
                $request['application_document'] = $this->curlAPiService->convertFileInBase64($request->file('application_documents'));
            } else {
                $request['application_document'] = "";
            }
            $request['application_no'] = $waterQualityComplaint->application_no;
            $request['user_id'] = (Auth::user()->user_id && Auth::user()->user_id != "") ? Auth::user()->user_id : Auth::user()->id;
            $newData = $request->except(['_token', 'id', 'application_documents']);
            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.water') . 'WaterBillMicroService/WaterbillApi/ApleSarkarService/RequestForUpdateComplaintOfWaterQuality', '');

            // Decode JSON string to PHP array
            $data = json_decode($data, true);

            if (isset($data['status']) && $data['status'] == "200") {
                // Access the application_no
                DB::commit();
                return [true];
            } else {
                DB::rollback();
                return [false, $data['error']];
            }
            // end of code to send data to department
        } catch (\Exception $e) {
            DB::rollback();
            Log::info($e);
            return [false, $e->getMessage()];
        }
    }
}
