<?php

namespace App\Services;

use App\Models\Marriage\MarriageRegistrationForm;
use App\Models\Marriage\MarriageRegistrationDetail;
use App\Models\Marriage\MarriageRegistrationGroomDetail;
use App\Models\Marriage\MarriageRegistrationBrideInformation;
use App\Models\Marriage\MarriageRegistrationPriestInformation;
use App\Models\Marriage\MarriageRegistrationWitnessInformation;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use App\Services\CurlAPiService;
use App\Services\AapaleSarkarLoginCheckService;
use App\Models\ServiceCredential;
use App\Models\Status;
use Exception;

class MarriageRegistrationService
{
    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 edit($id)
    {
        return MarriageRegistrationForm::with(['marriageRegistrationDetail', 'marriageRegistrationGroomDetail', 'marriageRegistrationBrideInformation', 'marriageRegistrationPriestInformation', 'marriageRegistrationWitnessInformation'])->first();
    }

    public function storeMarriageRegistrationForm($request)
    {
        Log::info('request', [$request->all()]);
        DB::beginTransaction();
        try {

            $user = Auth::user();
            $data = $request->all();


            // dd($data['user_id']);
            $data = $request->except(['application_no']);
            $data['service_id'] = "75";
            $data['registration_details_form_filled_date'] = date('Y-m-d', strtotime($data['registration_details_form_filled_date']));
            $data['registration_details_marriage_date_in_english'] = date('Y-m-d', strtotime($data['registration_details_marriage_date_in_english']));

            $data['groom_info_dob'] = date('Y-m-d', strtotime($data['groom_info_dob']));
            $data['bride_info_dob'] = date('Y-m-d', strtotime($data['bride_info_dob']));

            $existingForm = null;

            $data['groom_info_photo'] = $this->handleFileUpload($request, 'groom_info_photos', 'marriage/groom-information', $existingForm?->groom_info_photo, 'public');
            $data['groom_info_id_proof_file'] = $this->handleFileUpload($request, 'groom_info_id_proof_files', 'marriage/groom-information', $existingForm?->groom_info_id_proof_file);
            $data['groom_info_residential_proof_file'] = $this->handleFileUpload($request, 'groom_info_residential_proof_files', 'marriage/groom-information', $existingForm?->groom_info_residential_proof_file);
            $data['groom_info_age_proof_file'] = $this->handleFileUpload($request, 'groom_info_age_proof_files', 'marriage/groom-information', $existingForm?->groom_info_age_proof_file);
            $data['groom_info_upload_signature'] = $this->handleFileUpload($request, 'groom_info_upload_signatures', 'marriage/groom-information', $existingForm?->groom_info_upload_signature);
            $data['groom_info_upload_previous_status_proof'] = $this->handleFileUpload($request, 'groom_info_upload_previous_status_proofs', 'marriage/groom-information', $existingForm?->groom_info_upload_previous_status_proof);

            $data['bride_info_photo'] = $this->handleFileUpload($request, 'bride_info_photos', 'marriage/groom-information', $existingForm?->bride_info_photo);
            $data['bride_info_id_proof_file'] = $this->handleFileUpload($request, 'bride_info_id_proof_files', 'marriage/groom-information', $existingForm?->bride_info_id_proof_file);
            $data['bride_info_residential_proof_file'] = $this->handleFileUpload($request, 'bride_info_residential_proof_files', 'marriage/groom-information', $existingForm?->bride_info_residential_proof_file);
            $data['bride_info_age_proof_file'] = $this->handleFileUpload($request, 'bride_info_age_proof_files', 'marriage/groom-information', $existingForm?->bride_info_age_proof_file);
            $data['bride_info_upload_signature'] = $this->handleFileUpload($request, 'bride_info_upload_signatures', 'marriage/groom-information', $existingForm?->bride_info_upload_signature);
            $data['bride_info_upload_previous_status_proof'] = $this->handleFileUpload($request, 'bride_info_upload_previous_status_proofs', 'marriage/groom-information', $existingForm?->bride_info_upload_previous_status_proof);

            $data['priest_info_upload_signature'] = $this->handleFileUpload($request, 'priest_info_upload_signatures', 'marriage/priest-information', $existingForm?->priest_info_upload_signature);

            $data['first_witness_info_witness_photo'] = $this->handleFileUpload($request, 'first_witness_info_witness_photos', 'marriage/witness-information', $existingForm?->first_witness_info_witness_photo);
            $data['first_witness_info_upload_signature'] = $this->handleFileUpload($request, 'first_witness_info_upload_signatures', 'marriage/witness-information', $existingForm?->first_witness_info_upload_signature);
            $data['first_witness_info_upload_document'] = $this->handleFileUpload($request, 'first_witness_info_upload_documents', 'marriage/witness-information', $existingForm?->first_witness_info_upload_document);

            $data['second_witness_info_witness_photo'] = $this->handleFileUpload($request, 'second_witness_info_witness_photos', 'marriage/witness-information', $existingForm?->second_witness_info_witness_photo);
            $data['second_witness_info_upload_signature'] = $this->handleFileUpload($request, 'second_witness_info_upload_signatures', 'marriage/witness-information', $existingForm?->second_witness_info_upload_signature);
            $data['second_witness_info_upload_document'] = $this->handleFileUpload($request, 'second_witness_info_upload_documents', 'marriage/witness-information', $existingForm?->second_witness_info_upload_document);

            $data['third_witness_info_witness_photo'] = $this->handleFileUpload($request, 'third_witness_info_witness_photos', 'marriage/witness-information', $existingForm?->third_witness_info_witness_photo);
            $data['third_witness_info_upload_signature'] = $this->handleFileUpload($request, 'third_witness_info_upload_signatures', 'marriage/witness-information', $existingForm?->third_witness_info_upload_signature);
            $data['third_witness_info_upload_document'] = $this->handleFileUpload($request, 'third_witness_info_upload_documents', 'marriage/witness-information', $existingForm?->third_witness_info_upload_document);

            $data['registration_details_couple_photo'] = $this->handleFileUpload($request, 'registration_details_couple_photos', 'marriage/registration-details', $existingForm?->registration_details_couple_photo);
            $data['registration_details_wedding_card_image'] = $this->handleFileUpload($request, 'registration_details_wedding_card_images', 'marriage/registration-details', $existingForm?->registration_details_wedding_card_image);
            $data['prescribed_doc'] = $this->handleFileUpload($request, 'prescribed_docs', 'marriage/registration-details', $existingForm?->prescribed_doc);


            // Special case: affidavit file
            if ($request->hasFile('registration_from_affidavit_for_marriage_outside_maharashtras')) {
                $filePath = $request->file('registration_from_affidavit_for_marriage_outside_maharashtras')->store('marriage/registration-form', 'public');
                $data['registration_from_affidavit_for_marriage_outside_maharashtra'] = $filePath;
            }

            $data['user_id'] = Auth::user()->id;

            // dd($data);


            // dd($data['registration_details_marriage_date_in_english']);
            $marriageRegistrationForm = MarriageRegistrationForm::Create($data);

            if ($marriageRegistrationForm) {

                $applicationNo = 'MBMC/' . $data['service_id'] . '/' . $marriageRegistrationForm->id . '/' . date('dmY');
                $marriageRegistrationForm->application_no = $applicationNo;
                $marriageRegistrationForm->save();

                $status =  Status::create([
                    'service_id' => 75,
                    'department_id' => 3,
                    'table_id' => $marriageRegistrationForm->id,
                    'user_id' => Auth::user()->id
                ]);
                $this->commonservice->store_approval_hierarchies($marriageRegistrationForm, $user, $status);
            }


            DB::commit();
            return $marriageRegistrationForm;
        } catch (\Exception $e) {
            Log::error($e);
            DB::rollback();
            return false;
        }
    }

    // public function updateMarriage($request, $id)
    // {
    //     DB::beginTransaction();
    //     try {
    //         $marriageRegistrationForm = MarriageRegistrationForm::find($id);
    //         $data = $request->except(['_method', '_token']);
           
    //         $dateFields = [
    //         'registration_details_marriage_date_in_english',
    //         'groom_info_dob',
    //         'bride_info_dob',
    //         'first_witness_info_dob',
    //         'second_witness_info_dob',
    //         'third_witness_info_dob',
    //     ];

    //     foreach ($dateFields as $field) {
    //         if (!empty($data[$field])) {
    //             $data[$field] = $this->formatDate($data[$field]);
    //         }
    //     }

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

    public function updateMarriage($request, $id)
{
    DB::beginTransaction();
    try {
        $marriageRegistrationForm = MarriageRegistrationForm::find($id);

        if (!$marriageRegistrationForm) {
            return [false, 'Marriage record not found'];
        }

        $data = $request->except(['_method', '_token']);

        // Format date fields
        $dateFields = [
            'registration_details_marriage_date_in_english',
            'groom_info_dob',
            'bride_info_dob',
            'first_witness_info_dob',
            'second_witness_info_dob',
            'third_witness_info_dob',
        ];

        foreach ($dateFields as $field) {
            if (!empty($data[$field])) {
                $data[$field] = $this->formatDate($data[$field]);
            }
        }

        // Use forceFill to bypass Eloquent dirty check
        $marriageRegistrationForm->forceFill($data)->save();

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



    private function handleFileUpload($request, $fileInputName, $storagePath, $existingFilePath = null)
    {
        try {

            if ($request->hasFile($fileInputName)) {
                $filePath = $request->file($fileInputName)->store($storagePath, 'public');

                if ($existingFilePath && Storage::disk('public')->exists($existingFilePath)) {
                    Storage::disk('public')->delete($existingFilePath);
                }
                return $filePath;
            }

            return $existingFilePath;
        } catch (Exception $e) {
            Log::info('error in file upload', [$e->getMessage()]);
        }
    }

    private function formatDate($date)
    {
        if (!$date) return null;

        // If already Y-m-d just return it
        if (preg_match('/\d{4}-\d{2}-\d{2}/', $date)) return $date;

        // Convert DD-MM-YYYY → YYYY-MM-DD
        return date('Y-m-d', strtotime(str_replace('/', '-', $date)));
    }

}
