<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\PostApprovalFlow;
use App\PostApprovalFlowChangeLog;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;
use App\Lenders;

class ProductController extends Controller
{

    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    // For /admin/product
    public function index()
    {
        // Loads resources/views/admin/product-feature/product.blade.php
        return view('admin.product-feature.product');
    }

    // For /admin/product/add-document
    public function addDocument()
    {
        // Loads resources/views/admin/product-feature/AddDocument.blade.php
        return view('admin.product-feature.AddDocument');
    }

    public function postApprovalFlow(){
        $lenders = Lenders::where('status', 1)
                            ->select('id', 'name')
                            ->orderBy('name', 'asc')
                            ->get();
        return view('admin.product-feature.PostApprovalFlow', ['lenders' => $lenders]);
    }
   
    public function savePostApprovalFlow()
    {
        $data = $this->request->all();

        $criteria = $this->extractCriteria($data);

        $postApprovalFlow = $this->findPostApprovalFlow($criteria);

        $applicantData = $this->extractApplicantData($data, 'applicant');
        $coApplicantData = $this->extractApplicantData($data, 'coapplicant');

        if(isset($data['show_to_advisor']) && $data['show_to_advisor'] == 1){
            $this->sendNotificationToAdvisors($criteria, $applicantData, $coApplicantData, $data['lender_name']);
        }

        if ($postApprovalFlow) {
            $this->logChange('update', [
                'old' => [
                    'applicant' => $postApprovalFlow->applicant,
                    'co_applicant' => $postApprovalFlow->co_applicant,
                ],
                'new' => [
                    'applicant' => $applicantData,
                    'co_applicant' => $coApplicantData,
                ],
            ]);

            $postApprovalFlow->applicant = $applicantData;
            $postApprovalFlow->co_applicant = $coApplicantData;
            $postApprovalFlow->save();
        } else {
            $this->logChange('create', [
                'old' => null,
                'new' => [
                    'criteria' => $criteria,
                    'applicant' => $applicantData,
                    'co_applicant' => $coApplicantData,
                ],
            ]);

            $postApprovalFlow = new PostApprovalFlow();
            $postApprovalFlow->fill($criteria);
            $postApprovalFlow->applicant = $applicantData;
            $postApprovalFlow->co_applicant = $coApplicantData;
            $postApprovalFlow->save();
        }

        return response()->json([
            'success' => true,
            'message' => 'Data saved successfully!',
        ]);
    }

    private function extractCriteria(array $data): array
    {
        return [
            'type_customer' => $data['type_customer'] ?? null,
            'type_entity'   => $data['type_entity'] ?? null,
            'solar_for'     => $data['solar_for'] ?? null,
            'sub_category'  => $data['sub_category'] ?? null,
            'lender_id'     => $data['lender_id'] ?? null,
        ];
    }

    private function findPostApprovalFlow(array $criteria){
        return PostApprovalFlow::where($criteria)->first();
    }

    private function extractApplicantData(array $data, string $role): array
    {
        return [
            'vkyc'           => $data["vkyc_{$role}"] ?? null,
            'payment'        => $data["payment_{$role}"] ?? null,
            'mandate'        => $data["mandate_{$role}"] ?? null,
            'loan_agreement' => $data["loan_agreement_{$role}"] ?? null,
        ];
    }

    private function sendNotificationToAdvisors(array $criteria, array $applicantData, array $coApplicantData, string $lendername)
    {
        // Generate list items for applicant
        $applicantList = '';
        foreach ($applicantData as $key => $value) {
            if ($value == 1) {
                $applicantList .= '<li>' . ucfirst(str_replace('_', ' ', $key)) . '</li>';
            }
        }

        // Generate list items for co-applicant
        $coApplicantList = '';
        foreach ($coApplicantData as $key => $value) {
            if ($value == 1) {
                $coApplicantList .= '<li>' . ucfirst(str_replace('_', ' ', $key)) . '</li>';
            }
        }

        // Construct the HTML message
        $messageBody = '
            <p>Dear Advisor,</p>
            <p>
                We would like to inform you that there have been updates to the conditions associated with the solar financing application for your client. Please review the revised status for the key conditions below:
            </p>
            <p>
                <strong>In Post approval Digital Journey the following steps will be available for applicant if type of customer is '
                . htmlspecialchars($criteria['type_customer']) . ', type of entity is '
                . htmlspecialchars($criteria['type_entity']) . ', lender is '
                . htmlspecialchars($lendername) . ', solar financing for is '
                . htmlspecialchars($criteria['solar_for']) . ' and Sub-category of Solar Financing is '
                . htmlspecialchars($criteria['sub_category']) . ':</strong>
            </p>
            <ul>' . $applicantList . '</ul>
            <p>
                <strong>In Post approval Digital Journey the following steps will be available for co-applicant if type of customer is '
                . htmlspecialchars($criteria['type_customer']) . ', type of entity is '
                . htmlspecialchars($criteria['type_entity']) . ', lender is '
                . htmlspecialchars($lendername) . ', solar financing for is '
                . htmlspecialchars($criteria['solar_for']) . ' and Sub-category of Solar Financing is '
                . htmlspecialchars($criteria['sub_category']) . ':</strong>
            </p>
            <ul>' . $coApplicantList . '</ul>
            <p>
                These updates are as per the most recent configuration. Kindly note the post approval journey flow will be at merchant configuration and case to case level. If any step amongst the above shared condition is applicable at the case level then the same will be visible in the digital flow.
            </p>
            <p>
                If you have any questions or need further clarification, please feel free to contact product team.
            </p>
            <p>
                Thank you for your cooperation.
            </p>
            <p>
                Best regards,<br>
                Credit Fair
            </p>
        ';

        $advisorEmails = User::whereIn('user_type', [26, 37])
                        ->pluck('email')
                        ->toArray();
        
        if (!empty($advisorEmails)) {
            Mail::send('emails.reminders.basic_reminder',
                ['body' => $messageBody],
                function ($message) use ($advisorEmails) { 
                    $message->to($advisorEmails)
                            ->subject("Update Post approval Digital flow");
                }
            );
        }

        return $messageBody;
    }


    private function logChange(string $changeType, array $changes)
    {
        $log = new PostApprovalFlowChangeLog();
        $log->change_type = $changeType;
        $log['changes'] = $changes;
        $log->user_id = Auth::id();
        $log->save();
        return $log;
    }
    public function getPostApprovalFlow()
    {
        $data = $this->request->all();

        $criteria = $this->extractCriteria($data);

        $postApprovalFlow = $this->findPostApprovalFlow($criteria);

        if ($postApprovalFlow) {
            return response()->json([
                'found' => true,
                'loan_agreement_applicant' => $postApprovalFlow->applicant['loan_agreement'] ?? null,
                'loan_agreement_coapplicant' => $postApprovalFlow->co_applicant['loan_agreement'] ?? null,
                'vkyc_applicant' => $postApprovalFlow->applicant['vkyc'] ?? null,
                'vkyc_coapplicant' => $postApprovalFlow->co_applicant['vkyc'] ?? null,
                'payment_applicant' => $postApprovalFlow->applicant['payment'] ?? null,
                'payment_coapplicant' => $postApprovalFlow->co_applicant['payment'] ?? null,
                'mandate_applicant' => $postApprovalFlow->applicant['mandate'] ?? null,
                'mandate_coapplicant' => $postApprovalFlow->co_applicant['mandate'] ?? null,
            ]);
        } else {
            return response()->json(['found' => false]);
        }
    }

}