<?php

namespace App\Http\Controllers;

use App\Models\Ward;
use App\Models\Status;
use App\Models\SbiPayment;
use Illuminate\Http\Request;
use App\Services\CommonService;
use Illuminate\Support\Facades\DB;
use Barryvdh\Snappy\Facades\SnappyPdf;
use App\Services\MarriageRegistrationService;
use App\Models\Marriage\MarriageRegistrationForm;
use App\Http\Requests\Marriage\MarriageRegistrationFormRequest;
use App\Http\Requests\Marriage\MarriageRegistrationDetailsRequest;
use App\Models\Service;
use Illuminate\Support\Facades\Log;

class MarriageController extends Controller
{
    protected $marriageRegistrationService;
    protected $commonService;

    public function __construct(MarriageRegistrationService $marriageRegistrationService, CommonService $commonService)
    {
        set_time_limit(0);
        $this->middleware('permission:report.marriage-report')->only('marriagereport');
        $this->middleware('permission:report.services-report')->only('allreport');

        $this->marriageRegistrationService = $marriageRegistrationService;

    }

    public function index(Request $request)
    {
        return view('marriage.index');
    }

    public function create()
    {

        $options = Ward::get();
        return view('marriage.create', compact('options'));
    }

    // public function edit($id)
    // {
    //     $marriageRegistration = $this->marriageRegistrationService->edit(decrypt($id));
    //     // return $marriageRegistration;
    //     return view('marriage.edit')->with([
    //         'marriageRegistration' => $marriageRegistration
    //     ]);
    // }

    public function edit($id)
    {
        $id = decrypt($id);

        $data = MarriageRegistrationForm::findOrFail($id);

        // return $data;
        $status = Status::where('table_id', $id)
            ->where('service_id', $data->service_id)
            ->first();

        $options = Ward::get();

        return view('marriage.edit')->with([
            'data' => $data,
            'status' => $status,
            'options' => $options
        ]);
    }

    // store marriage registration form
    public function storeMarriageeRgistrationForm(MarriageRegistrationFormRequest $request)
    {
     
        Log::info('Witness Request Data', $request->all());

        $storeMarriageRegistrationForm = $this->marriageRegistrationService->storeMarriageRegistrationForm($request);

        if ($storeMarriageRegistrationForm) {
            return response()->json([
                'success' => 'Application Submitted successfully',
                'data' => $storeMarriageRegistrationForm
            ]);
        } else {
            return response()->json([
                'error' => 'Something went wrong, please try again'
            ]);
        }
    }

    public function update(Request $request, $id)
    {
        $updatemarriage = $this->marriageRegistrationService->updateMarriage($request, $id);

        if ($updatemarriage) {
            return response()->json([
                'success' => 'Marriage Details updated successfully'
            ]);
        } else {
            return response()->json([
                'error' => 'Something went wrong, please try again'
            ]);
        }
    }

    public function show($id)
    {
        $data = MarriageRegistrationForm::with('user')->findOrFail(decrypt($id));
        $pdf = SnappyPdf::loadView('marriage.marriagecertificate', ['data' => $data]);
        $pdf->setPaper('a4')
            ->setOption('margin-top', 10)
            ->setOption('margin-bottom', 10)
            ->setOption('margin-left', 5)
            ->setOption('margin-right', 5)
            ->setOption('enable-smart-shrinking', true)
            ->setOption('disable-smart-shrinking', false)
            ->setOption('no-stop-slow-scripts', true)
            // ->setOption('footer-right', now()->format('d-m-Y h:i:s'))
            ->setOption('footer-left', 'Page: [page] of [toPage]');
        return $pdf->inline('certificate.pdf');
    }

    public function generateReceipt($id)
    {
        $data = MarriageRegistrationForm::with('user')->findOrFail(decrypt($id));
        $paymentdata = SbiPayment::Where('table_id', $data->id)->where('service_id', $data->service_id)->first();
        $pdf = SnappyPdf::loadView('marriage.receipt', ['data' => $data, 'paymentdata' => $paymentdata]);

        $pdf->setPaper('a4')
            ->setOption('margin-top', 10)
            ->setOption('margin-bottom', 10)
            ->setOption('margin-left', 5)
            ->setOption('margin-right', 5)
            ->setOption('enable-smart-shrinking', true)
            ->setOption('disable-smart-shrinking', false)
            ->setOption('no-stop-slow-scripts', true)
            // ->setOption('footer-right', now()->format('d-m-Y h:i:s'))
            ->setOption('footer-left', 'Page: [page] of [toPage]');

        return $pdf->inline('receipt.pdf');
    }

    public function marriagereport()
    {
        $data = MarriageRegistrationForm::where('service_id', 75)->get();
        $status = Status::where('service_id', 75)->get();

        return view('marriage.report', compact('data', 'status'));
    }

    public function goshwar1($id)
    {
        $record = MarriageRegistrationForm::findOrFail($id);

        $pdf = SnappyPdf::loadView('marriage.goshwar1', compact('record'));

        $pdf->setPaper('a4')
            ->setOption('margin-top', 10)
            ->setOption('margin-bottom', 10)
            ->setOption('margin-left', 5)
            ->setOption('margin-right', 5)
            ->setOption('enable-smart-shrinking', true)
            ->setOption('disable-smart-shrinking', false)
            ->setOption('no-stop-slow-scripts', true)
            // ->setOption('footer-right', now()->format('d-m-Y h:i:s'))
            ->setOption('footer-left', 'Page: [page] of [toPage]');

        return $pdf->inline('goshwar1.pdf');
    }

    public function goshwar3($id)
    {
        $record = MarriageRegistrationForm::findOrFail($id);

        $pdf = SnappyPdf::loadView('marriage.goshwar3', compact('record'));

        $pdf->setPaper('a4')
            ->setOption('margin-top', 10)
            ->setOption('margin-bottom', 10)
            ->setOption('margin-left', 5)
            ->setOption('margin-right', 5)
            ->setOption('enable-smart-shrinking', true)
            ->setOption('disable-smart-shrinking', false)
            ->setOption('no-stop-slow-scripts', true)
            // ->setOption('footer-right', now()->format('d-m-Y h:i:s'))
            ->setOption('footer-left', 'Page: [page] of [toPage]');

        return $pdf->inline('goshwar3.pdf');
    }



    // store marriage registration details
    // public function storeMarriageRegistrationDetails(MarriageRegistrationDetailsRequest $request)
    // {
    //     $storeMarriageRegistrationDetails = $this->marriageRegistrationService->storeMarriageRegistrationDetails($request);

    //     if ($storeMarriageRegistrationDetails) {
    //         return response()->json([
    //             'success' => 'Marriage created successfully',
    //             'data' => $storeMarriageRegistrationDetails
    //         ]);
    //     } else {
    //         return response()->json([
    //             'error' => 'Something went wrong, please try again'
    //         ]);
    //     }
    // }

    // store groom information
    // public function storeGroomInformation(GroomInformationRequest $request)
    // {
    //     $storeGroomInformation = $this->marriageRegistrationService->storeGroomInformation($request);

    //     if ($storeGroomInformation) {
    //         return response()->json([
    //             'success' => 'Marriage created successfully',
    //             'data' => $storeGroomInformation
    //         ]);
    //     } else {
    //         return response()->json([
    //             'error' => 'Something went wrong, please try again',
    //         ]);
    //     }
    // }

    // store bride information
    // public function storeBrideInformation(BrideInformationRequest $request)
    // {
    //     $storeBrideInformation = $this->marriageRegistrationService->storeBrideInformation($request);

    //     if ($storeBrideInformation) {
    //         return response()->json([
    //             'success' => 'Marriage created successfully',
    //             'data' => $storeBrideInformation
    //         ]);
    //     } else {
    //         return response()->json([
    //             'error' => 'Something went wrong, please try again',
    //         ]);
    //     }
    // }

    // store priest information
    // public function storePriestInformation(PriestInformationRequest $request)
    // {
    //     $storePriestInformation = $this->marriageRegistrationService->storePriestInformation($request);

    //     if ($storePriestInformation) {
    //         return response()->json([
    //             'success' => 'Marriage created successfully',
    //             'data' => $storePriestInformation
    //         ]);
    //     } else {
    //         return response()->json([
    //             'error' => 'Something went wrong, please try again',
    //         ]);
    //     }
    // }

    // store witness information
    // public function storeWitnessInformation(WitnessInformationRequest $request)
    // {
    //     $storeWitnessInformation = $this->marriageRegistrationService->storeWitnessInformation($request);

    //     if ($storeWitnessInformation) {
    //         return response()->json([
    //             'success' => 'Marriage created successfully',
    //             'data' => $storeWitnessInformation
    //         ]);
    //     } else {
    //         return response()->json([
    //             'error' => 'Something went wrong, please try again',
    //         ]);
    //     }
    // }


    public function allreport(Request $request)
    {
        $services = Service::with('services')->where('is_parent', 0)->get();

        $data = [];

        // Get filter inputs
        $departmentId = $request->department_id;
        $subServices = Service::with('mainService')->whereNotNull('service_id');

        if (!empty($departmentId)) {
            $subServices->where('service_id', $departmentId);
        }
        $subServices = $subServices->get();
        $fromDate = $request->from_date;
        $toDate = $request->to_date;

        foreach ($subServices as $subService) {
            if (!$subService->table_name) continue;

            $tableName = $subService->table_name;
            // Build base query with left join
            $tableData = DB::table($tableName . ' as t')
                ->leftJoin('statuses as s', function ($join) {
                    $join->on('s.table_id', '=', 't.id')
                        ->whereColumn('s.service_id', '=', 't.service_id');
                });

            // Apply date filters if provided
            if ($fromDate) {
                $tableData->whereDate('t.created_at', '>=', $fromDate);
            }
            if ($toDate) {
                $tableData->whereDate('t.created_at', '<=', $toDate);
            }

            // Count pending
            $pending = (clone $tableData)->where('s.status', 0)->count();

            // Count approved
            $approved = (clone $tableData)->where('s.status', 1)->count();

            // Count rejected
            $rejected = (clone $tableData)->where('s.status', 2)->count();

            // Total records
            $total = $tableData->count();

            $data[] = [
                'department_name' => $subService->mainService->name ?? '-',
                'service_name' => $subService->name,
                'total' => $total,
                'approved' => $approved,
                'rejected' => $rejected,
                'pending' => $pending,
            ];
        }


        return view('all-service-report')->with([
            'reportData' => collect($data),
            'services' => $services,
            'subServices' => $subServices
        ]);
    }
}
