<?php

namespace App\Services\WaterDepartment;

use App\Mail\SendMail;
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\Mail;
use Illuminate\Support\Facades\Storage;
use App\Services\AapaleSarkarLoginCheckService;
use App\Models\WaterDepartment\WaterChangeOwnership;

class ChangeOwnershipService
{
    protected $curlAPiService;
    protected $aapaleSarkarLoginCheckService;

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

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

//         try {
//             $user = Auth::user();
//             $request['user_id'] = Auth::user()->id;
//             $request['service_id'] = "23";
//             $request['ward_area'] = WaterPrabhagWards::where('ward_name', $request->zone)->value('id'); // returns a single value instead of a collection

           
//             if ($request->hasFile('existing_water_bill')) {
//     $request['existing_water_bill'] = $request->file('existing_water_bill')
//         ->store('WaterDepartment/ChangeOwnership', 'public');
// }

// if ($request->hasFile('tax_bill_or_transfer_order')) {
//     $request['tax_bill_or_transfer_order'] = $request->file('tax_bill_or_transfer_order')
//         ->store('WaterDepartment/ChangeOwnership', 'public');
// }

// if ($request->hasFile('stamp_paper_or_noobjection_cert')) {
//     $request['stamp_paper_or_noobjection_cert'] = $request->file('stamp_paper_or_noobjection_cert')
//         ->store('WaterDepartment/ChangeOwnership', 'public');
// }

// if ($request->hasFile('electricity_bill_or_pan_card')) {
//     $request['electricity_bill_or_pan_card'] = $request->file('electricity_bill_or_pan_card')
//         ->store('WaterDepartment/ChangeOwnership', 'public');
// }



//             $waterChangeOwnership = WaterChangeOwnership::create($request->except('application_no'));

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

//                 $status = Status::create([
//                     'user_id' => $request['user_id'],
//                     'service_id' =>23,
//                     'department_id' =>5,
//                     'table_id' => $waterChangeOwnership->id
//                 ]);
//             }

//             $this->commonservice->store_approval_hierarchies($waterChangeOwnership, $user, $status);

//             // code to send data to department
//             if ($request->hasFile('application_document')) {
//     $request['application_document'] = $request->file('application_document')
//         ->store('WaterDepartment/ChangeOwnership', 'public'); // store in storage/public
// } else {
//     $request['application_document'] = null;
// }
            

//             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 {
        $user = Auth::user();

        // Basic data
        $data = $request->except('application_no'); 
        $data['user_id'] = $user->id;
        $data['service_id'] = "23";
        $data['ward_area'] = WaterPrabhagWards::where('ward_name', $request->zone)->value('id');

        // File fields
        $fileFields = [
            'existing_water_bill',
            'tax_bill_or_transfer_order',
            'stamp_paper_or_noobjection_cert',
            'electricity_bill_or_pan_card',
            'application_document'
        ];

        $uploadFolder = 'WaterDepartment/ChangeOwnership';

        foreach ($fileFields as $field) {
            if ($request->hasFile($field)) {
                $file = $request->file($field);
                $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();

                // Move file to storage/app/public/WaterDepartment/ChangeOwnership
                $file->storeAs($uploadFolder, $filename, 'public');

                // Save relative path for DB
                $data[$field] = $uploadFolder . '/' . $filename;
            } else {
                $data[$field] = null;
            }
        }

        // Insert record
        $waterChangeOwnership = WaterChangeOwnership::create($data);

        if ($waterChangeOwnership) {
            // Generate application number
            $waterChangeOwnership->application_no = 'MBMC/' . $data['service_id'] . '/' . $waterChangeOwnership->id . '/' . date('dmY');
            $waterChangeOwnership->save();

            // Create status
            $status = Status::create([
                'user_id' => $data['user_id'],
                'service_id' => 23,
                'department_id' => 5,
                'table_id' => $waterChangeOwnership->id
            ]);

            // Approval hierarchy
            $this->commonservice->store_approval_hierarchies($waterChangeOwnership, $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 WaterChangeOwnership::find($id);
    }

    // public function update_old($request, $id)
    // {
    //     DB::beginTransaction();
    //     try {
    //         // Find the existing record
    //         $waterChangeOwnership = WaterChangeOwnership::findOrFail($id);
    //         // Handle file uploads and update original file names
    //         if ($request->hasFile('application_documents')) {
    //             if ($waterChangeOwnership && Storage::exists($waterChangeOwnership->application_document)) {
    //                 Storage::delete($waterChangeOwnership->application_document);
    //             }
    //             $request['application_document'] = $request->application_documents->store('WaterDepartment/ChangeOwnership');
    //         }
    //         if ($request->hasFile('ownership_documents')) {
    //             if ($waterChangeOwnership && Storage::exists($waterChangeOwnership->ownership_document)) {
    //                 Storage::delete($waterChangeOwnership->ownership_document);
    //             }
    //             $request['ownership_document'] = $request->ownership_documents->store('WaterDepartment/ChangeOwnership');
    //         }
    //         if ($request->hasFile('nodues_documents')) {
    //             if ($waterChangeOwnership && Storage::exists($waterChangeOwnership->nodues_document)) {
    //                 Storage::delete($waterChangeOwnership->nodues_document);
    //             }
    //             $request['nodues_document'] = $request->nodues_documents->store('WaterDepartment/ChangeOwnership');
    //         }
    //         // Update the rest of the fields
    //         $waterChangeOwnership->update($request->all());


    //         // code to send data to department
    //         if ($request->hasFile('nodues_documents')) {
    //             $request['nodues_document'] = $this->curlAPiService->convertFileInBase64($request->file('nodues_documents'));
    //         } else {
    //             $request['nodues_document'] = "";
    //         }
    //         if ($request->hasFile('ownership_documents')) {
    //             $request['ownership_document'] = $this->curlAPiService->convertFileInBase64($request->file('ownership_documents'));
    //         } else {
    //             $request['ownership_document'] = "";
    //         }
    //         if ($request->hasFile('nodues_documents')) {
    //             $request['nodues_document'] = $this->curlAPiService->convertFileInBase64($request->file('nodues_documents'));
    //         } else {
    //             $request['nodues_document'] = "";
    //         }
    //         $request['application_no'] = $waterChangeOwnership->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', 'ownership_documents', 'nodues_documents']);
    //         $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.water') . 'WaterBillMicroService/WaterbillApi/ApleSarkarService/RequestForUpdateChangeInOwnership', '');

    //         // 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()];
    //     }
    // }


    public function update($request, $id)
{
    DB::beginTransaction();
    try {
        $waterChangeOwnership = WaterChangeOwnership::findOrFail($id);

        // Prepare data array for update
        $data = $request->except(['_token', 'id', 'application_documents', 'ownership_documents', 'nodues_documents']);

        // File fields mapping: form field => DB column
        $fileFields = [
            'application_documents' => 'application_document',
            'ownership_documents'  => 'ownership_document',
            'nodues_documents'     => 'nodues_document',
        ];

        $uploadFolder = 'WaterDepartment/ChangeOwnership';

        foreach ($fileFields as $formField => $dbField) {
            if ($request->hasFile($formField)) {
                // Delete old file if exists
                if ($waterChangeOwnership->{$dbField} && Storage::exists($waterChangeOwnership->{$dbField})) {
                    Storage::delete($waterChangeOwnership->{$dbField});
                }

                // Store new file
                $file = $request->file($formField);
                $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
                $file->storeAs($uploadFolder, $filename, 'public');

                // Save relative path for DB
                $data[$dbField] = $uploadFolder . '/' . $filename;
            }
        }

        // Update record
        $waterChangeOwnership->update($data);

        // code to send data to department (keep as-is)
        $newData = $data;
        $newData['application_no'] = $waterChangeOwnership->application_no;
        $newData['user_id'] = (Auth::user()->user_id && Auth::user()->user_id != "") ? Auth::user()->user_id : Auth::user()->id;

        $dataResponse = $this->curlAPiService->sendPostRequestInObject(
            $newData,
            config('rtsapiurl.water') . 'WaterBillMicroService/WaterbillApi/ApleSarkarService/RequestForUpdateChangeInOwnership',
            ''
        );

        $dataResponse = json_decode($dataResponse, true);

        if (isset($dataResponse['status']) && $dataResponse['status'] == "200") {
            DB::commit();
            return [true];
        } else {
            DB::rollback();
            return [false, $dataResponse['error']];
        }

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