<?php

namespace App\Services\ConstructionDepartment;

use App\Models\Status;
use App\Services\CommonService;
use App\Services\CurlAPiService;
use App\Models\ServiceCredential;
use App\Models\WaterPrabhagWards;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Services\AapaleSarkarLoginCheckService;
use App\Models\ConstructionDepartment\ConstructionDrainageConnection;

class DrainageConnectionService
{
    protected $curlAPiService;
    protected $aapaleSarkarLoginCheckService;

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



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

    try {
        $user = Auth::user();
        $serviceId = 188;

        // ✅ Convert request to array safely
        $data = $request->except('application_no');

        // ✅ Add computed fields
        $data['user_id'] = $user->id;
        $data['service_id'] = $serviceId;
        $data['ward_area'] = WaterPrabhagWards::where('ward_name', $request->zone)->value('id');

        // ✅ Handle file uploads (if exist)
        $uploadPath = 'construction-department/drainage-connection';

        if ($request->hasFile('upload_prescribed_formats')) {
            $data['upload_prescribed_format'] = $request->file('upload_prescribed_formats')->store($uploadPath, 'public');
        }
        if ($request->hasFile('upload_no_dues_certificates')) {
            $data['upload_no_dues_certificate'] = $request->file('upload_no_dues_certificates')->store($uploadPath, 'public');
        }
        if ($request->hasFile('upload_property_ownerships')) {
            $data['upload_property_ownership'] = $request->file('upload_property_ownerships')->store($uploadPath, 'public');
        }
        if ($request->hasFile('oc_cc_docs')) {
            $data['oc_cc_doc'] = $request->file('oc_cc_docs')->store($uploadPath, 'public');
        }

        // ✅ Create main record
        $constructionDrainageConnection = ConstructionDrainageConnection::create($data);

        // ✅ Generate application number (correct format)
        if ($constructionDrainageConnection) {
            $applicationNo = 'MBMC/' . $serviceId . '/' . $constructionDrainageConnection->id . '/' . date('dmY');

            $constructionDrainageConnection->update([
                'application_no' => $applicationNo
            ]);

            // ✅ Create status record
            $status = Status::create([
                'user_id' => $user->id,
                'service_id' => $serviceId,
                'department_id' => 5,
                'table_id' => $constructionDrainageConnection->id,
            ]);

            // ✅ Store approval hierarchy
            $this->commonService->store_approval_hierarchies($constructionDrainageConnection, $user, $status);
        }

        // ✅ Aaple Sarkar Integration (only if user is aapale sarkar user)
        if ($user->is_aapale_sarkar_user) {
            $aapaleSarkarCredential = ServiceCredential::where('dept_service_id', $serviceId)->first();

            if ($aapaleSarkarCredential) {
                $serviceDay = $aapaleSarkarCredential->service_day ?? 20;

                $send = $this->aapaleSarkarLoginCheckService->encryptAndSendRequestToAapaleSarkar(
                    $user->trackid,
                    $aapaleSarkarCredential->client_code,
                    $user->user_id,
                    $aapaleSarkarCredential->service_id,
                    $applicationNo, // ✅ send correct format number
                    'N', 'NA', 'N', 'NA',
                    $serviceDay,
                    date('Y-m-d', strtotime("+$serviceDay days")),
                    config('rtsapiurl.amount'),
                    config('rtsapiurl.requestFlag'),
                    config('rtsapiurl.applicationStatus'),
                    config('rtsapiurl.applicationPendingStatusTxt'),
                    $aapaleSarkarCredential->ulb_id,
                    $aapaleSarkarCredential->ulb_district,
                    'NA', 'NA', 'NA',
                    $aapaleSarkarCredential->check_sum_key,
                    $aapaleSarkarCredential->str_key,
                    $aapaleSarkarCredential->str_iv,
                    $aapaleSarkarCredential->soap_end_point_url,
                    $aapaleSarkarCredential->soap_action_app_status_url
                );

                if (!$send) {
                    throw new \Exception('Failed to send Aapale Sarkar request');
                }
            }
        }

        DB::commit();
        return true;

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


    

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

    public function update($request, $id)
    {
        DB::beginTransaction();

        try {
            // Find the existing record
            $constructionDrainageConnection = ConstructionDrainageConnection::findOrFail($id);
            // Handle file uploads and update original file names
            if ($request->hasFile('upload_prescribed_formats')) {
                if ($constructionDrainageConnection && Storage::exists($constructionDrainageConnection->upload_prescribed_format)) {
                    Storage::delete($constructionDrainageConnection->upload_prescribed_format);
                }
                $request['upload_prescribed_format'] = $request->upload_prescribed_formats->store('construction-department/drainage-connection','public');
            }
            if ($request->hasFile('upload_no_dues_certificates')) {
                if ($constructionDrainageConnection && Storage::exists($constructionDrainageConnection->upload_no_dues_certificate)) {
                    Storage::delete($constructionDrainageConnection->upload_no_dues_certificate);
                }
                $request['upload_no_dues_certificate'] = $request->upload_no_dues_certificates->store('construction-department/drainage-connection','public');
            }
            if ($request->hasFile('upload_property_ownerships')) {
                if ($constructionDrainageConnection && Storage::exists($constructionDrainageConnection->upload_property_ownership)) {
                    Storage::delete($constructionDrainageConnection->upload_property_ownership);
                }
                $request['upload_property_ownership'] = $request->upload_property_ownerships->store('construction-department/drainage-connection','public');
            }
            $constructionDrainageConnection->update($request->all());



            // code to send data to department
            // if ($request->hasFile('upload_prescribed_formats')) {
            //     $request['upload_prescribed_format'] = $this->curlAPiService->convertFileInBase64($request->file('upload_prescribed_formats'));
            // } else {
            //     $request['upload_prescribed_format'] = "";
            // }
            // if ($request->hasFile('upload_no_dues_certificates')) {
            //     $request['upload_no_dues_certificate'] = $this->curlAPiService->convertFileInBase64($request->file('upload_no_dues_certificates'));
            // } else {
            //     $request['upload_no_dues_certificate'] = "";
            // }
            // if ($request->hasFile('upload_property_ownerships')) {
            //     $request['upload_property_ownership'] = $this->curlAPiService->convertFileInBase64($request->file('upload_property_ownerships'));
            // } else {
            //     $request['upload_property_ownership'] = "";
            // }
            // $request['application_no'] = $constructionDrainageConnection->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', 'upload_prescribed_formats', 'upload_no_dues_certificates', 'upload_property_ownerships']);
            // $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.water') . 'AapaleSarkarAPI/NewTaxation.asmx/RequestForUpdateNewTaxation', 'NewTaxation');

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

            // if ($data['d']['Status'] == "200") {
            // Access the application_no
            DB::commit();
            return true;
            // } else {
            //     DB::rollback();
            //     return false;
            // }
            // end of code to send data to department
        } catch (\Exception $e) {
            DB::rollback();
            Log::info($e);
            return false;
        }
    }
}
