<?php

namespace App\Http\Controllers\Frontend;

use App\Enums\ThemeList;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Rules\CustomRecaptcha;
use App\Traits\GlobalMailTrait;
use Modules\Faq\app\Models\Faq;
use Illuminate\Http\JsonResponse;
use Modules\Blog\app\Models\Blog;
use Modules\Award\app\Models\Award;
use Modules\Brand\app\Models\Brand;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Modules\OurTeam\app\Models\OurTeam;
use Modules\Project\app\Models\Project;
use Modules\Shop\app\Models\Product;
use Modules\Service\app\Models\Service;
use Modules\Frontend\app\Models\Section;
use Illuminate\Support\Facades\Validator;
use Modules\Testimonial\app\Models\Testimonial;
use Modules\PageBuilder\app\Models\CustomizeablePage;
use Modules\SiteAppearance\app\Models\SectionSetting;
use Modules\Subscription\app\Models\SubscriptionPlan;
use Modules\GlobalSetting\app\Models\CustomPagination;

class HomePageController extends Controller {
    use GlobalMailTrait;

    function index(): View {
        $sectionSetting = SectionSetting::first();

        $theme_name = Session::has('demo_theme') ? Session::get('demo_theme') : DEFAULT_HOMEPAGE;
        $sections = Section::whereHas("home", function ($q) use ($theme_name) {
            $q->where('slug', $theme_name);
        })->get();

        $hero = $sections->where('name', 'hero_section')->first();
        $aboutSection = $sections->where('name', 'about_section')->first();

        /*$faqs = Faq::select('id')->with(['translation' => function ($query) {
            $query->select('faq_id', 'question', 'answer');
        }])->active()->latest()->take(4)->get();*/

        $products = Product::select('id', 'slug', 'image')->with(['translation' => function ($query) {
            $query->select('product_id', 'title');
		}])->active()->latest()->take(7)->get();
		
        /*$teams = OurTeam::select('name', 'slug', 'designation', 'image')->active()->latest()->take(4)->get();

        $testimonialSection = $sections->where('name', 'testimonial_section')->first();
        $testimonials = Testimonial::select('id')->with(['translation' => function ($query) {
            $query->select('testimonial_id', 'name', 'designation', 'comment');
        }])->active()->latest()->take(4)->get();*/

        /*$latest_blogs = Blog::select('id', 'blog_category_id', 'slug', 'image', 'created_at')->with([
            'translation'          => function ($query) {
                $query->select('blog_id', 'title');
            },
            'category'             => function ($query) {
                $query->select('id', 'slug');
            },
            'category.translation' => function ($query) {
                $query->select('blog_category_id', 'title');
            },
        ])->whereHas('category', function ($query) {
            $query->active();
        })->active()->homepage()->latest()->take(5)->get();*/

        $bannerSection = $sections->where('name', 'banner_section')->first();
        //$brands = Brand::select('name', 'image', 'url')->active()->take(8)->get();

        /*$awards = Award::select('id', 'url')->with([
            'translation' => function ($query) {
                $query->select('award_id', 'year', 'title', 'sub_title', 'tag');
            },
        ])->active()->latest()->take(4)->get();

        $services = Service::select('id', 'slug', 'icon')->with(['translation' => function ($query) {
            $query->select('service_id', 'title', 'short_description', 'btn_text');
        }])->active()->latest()->take(4)->get();

        $servicefeatureSection = $sections->where('name', 'service_feature_section')->first();

        $chooseUsSection = $sections->where('name', 'choose_us_section')->first();

        $counterSection = $sections->where('name', 'counter_section')->first();

        $plans = SubscriptionPlan::select('id', 'plan_price','expiration_date','button_url')->with([
            'translation'          => function ($query) {
                $query->select( 'subscription_plan_id','plan_name','short_description','description','button_text');
            },
        ])->active()->orderBy('serial')->take(3)->get();*/
		
		$individualCurrentAccount = CustomizeablePage::with('translation')->whereSlug('individual-current-account')->whereStatus(true)->first();
		$individualSavingAccount = CustomizeablePage::with('translation')->whereSlug('individual-saving-account')->whereStatus(true)->first();
		$corporateCurrentAccount = CustomizeablePage::with('translation')->whereSlug('corporate-current-account')->whereStatus(true)->first();
		$wpsCurrentAccount = CustomizeablePage::with('translation')->whereSlug('wps-current-account')->whereStatus(true)->first();

        return view('frontend.home.' . $theme_name . '.index', compact(
            'sectionSetting',
            'hero',
            'aboutSection',
            'products',
            'bannerSection',
			'individualCurrentAccount',
			'individualSavingAccount',
			'corporateCurrentAccount',
			'wpsCurrentAccount',
        ));
    }
    function changeTheme(string $theme) {
        if (cache()->get('setting')?->show_all_homepage != 1) {
            abort(404);
        }
        foreach (ThemeList::cases() as $enumTheme) {
            if ($theme == $enumTheme->value) {
                Session::put('demo_theme', $enumTheme->value);
                break;
            }
        }
        return redirect('/');
    }
    public function about(): View {
        $theme_name = DEFAULT_HOMEPAGE;

        $counterSection = Section::whereHas("home", function ($q) use ($theme_name) {
            $q->where('slug', $theme_name);
        })->where('name', 'counter_section')->first();

        $chooseUsSection = Section::whereHas("home", function ($q) use ($theme_name) {
            $q->where('slug', $theme_name);
        })->where('name', 'choose_us_section')->first();

        $awards = Award::select('id', 'url')->with([
            'translation' => function ($query) {
                $query->select('award_id', 'year', 'title', 'sub_title', 'tag');
            },
        ])->active()->latest()->take(4)->get();
        $teams = OurTeam::select('name', 'slug', 'designation', 'image')->active()->latest()->take(4)->get();
        $brands = Brand::select('name', 'image', 'url')->active()->take(8)->get();
		
		$about = CustomizeablePage::with('translation')->whereSlug('about-us')->whereStatus(true)->first();

        return view('frontend.pages.about', compact('counterSection','chooseUsSection','teams','brands','awards','about'));

    }
    public function onlineBanking(): View {
		
		$onlineBanking = "";

        return view('frontend.pages.online-banking', compact('onlineBanking'));

    }
    public function LoanCalculator(): View {
		
		$LoanCalculator = "";

        return view('frontend.pages.loan-calculator', compact('LoanCalculator'));

    }
    public function DepositCalculator(): View {
		
		$DepositCalculator = "";

        return view('frontend.pages.deposit-calculator', compact('DepositCalculator'));

    }
    
    
    public function keyFactsStatement(): View {
		
		$keyFactsStatement = "";

        return view('frontend.pages.key-facts-statement', compact('keyFactsStatement'));

    }
    public function scheduleCharges(): View {
		
		$scheduleCharges = "";

        return view('frontend.pages.schedule-of-charges', compact('scheduleCharges'));

    }
    public function complaint(): View {
		
		$complaint = "";

        return view('frontend.pages.complaint', compact('complaint'));

    }
    
    public function eservices(): View {
		
		$eservices = CustomizeablePage::with('translation')->whereSlug('eservice')->whereStatus(true)->first();

        return view('frontend.pages.eservices', compact('eservices'));

    }
    public function fatca(): View {
		
		$fatca = CustomizeablePage::with('translation')->whereSlug('fatca-crs')->whereStatus(true)->first();
		$csr = CustomizeablePage::with('translation')->whereSlug('csr')->whereStatus(true)->first();

        return view('frontend.pages.fatca-crs', compact('fatca','csr'));

    }
    public function applicationForms(): View {
		
		$applicationForms = "";

        return view('frontend.pages.application-forms', compact('applicationForms'));

    }
    public function iban(): View {
		
		$iban = CustomizeablePage::with('translation')->whereSlug('iban-calculator')->whereStatus(true)->first();;

        return view('frontend.pages.iban', compact('iban'));

    }
	/*public function generateIban(Request $request)
    {
        $request->validate([
            'account_number' => 'required|digits_between:1,19',
        ]);

        $accountNumber = str_pad(preg_replace('/\D/', '', $request->account_number), 19, "0", STR_PAD_LEFT);
        $bankCode = "013"; // Bank Saderat Iran
        $ibanBase = $bankCode . $accountNumber . "AE00";
        $converted = '';
        foreach (str_split($ibanBase) as $char) {
            $converted .= ctype_alpha($char) ? (ord($char) - 55) : $char;
        }

        $mod = bcmod($converted, 97);
        $checkDigits = str_pad(98 - $mod, 2, "0", STR_PAD_LEFT);
        $iban = "AE{$checkDigits}{$bankCode}{$accountNumber}";

        return response()->json(['iban' => $iban]);
    }*/
	public function generateIban(Request $request)
{
    $request->validate([
        'account_number' => ['required', 'digits:13']
    ]);

    $input = preg_replace('/\D/', '', $request->account_number);

    // Extract parts
    $branchCode = substr($input, 0, 4);
    $accountPart = substr($input, 4, 6);
    $suffix = substr($input, -3);

    // Valid branch codes
    $validBranchCodes = ['1741', '2533', '2624', '2690', '2776', '2900', '4350', '2898', '3535'];

    // Validate branch code and suffix
    if (!in_array($branchCode, $validBranchCodes) || (int)$suffix < 1 || (int)$suffix > 199) {
        return response()->json([
            'error' => 'Account number is invalid.'
        ], 422);
    }

    // IBAN Construction
    $bankCode = "013"; // Bank Saderat Iran UAE
    $accountNumber = str_pad($input, 16, "0", STR_PAD_LEFT); // total 19-digit account part

    $ibanBase = $bankCode . $accountNumber . "AE00";
    $converted = '';
    foreach (str_split($ibanBase) as $char) {
        $converted .= ctype_alpha($char) ? (ord($char) - 55) : $char;
    }

    $mod = bcmod($converted, 97);
    $checkDigits = str_pad(98 - $mod, 2, "0", STR_PAD_LEFT);
    $iban = "AE{$checkDigits}{$bankCode}{$accountNumber}";

    return response()->json([
        'iban' => $iban
    ]);
}

    public function career(): View {
		
		$career = "";

        return view('frontend.pages.career', compact('career'));

    }
    public function awarness(): View {

		$awarness1 = CustomizeablePage::with('translation')->whereSlug('awareness-security-introduction')->whereStatus(true)->first();
		$awarness2 = CustomizeablePage::with('translation')->whereSlug('awareness-security-2')->whereStatus(true)->first();
		$awarness3 = CustomizeablePage::with('translation')->whereSlug('awareness-security-3')->whereStatus(true)->first();
		$awarness4 = CustomizeablePage::with('translation')->whereSlug('awareness-security-4')->whereStatus(true)->first();
		$awarness5 = CustomizeablePage::with('translation')->whereSlug('awareness-security-5')->whereStatus(true)->first();

        return view('frontend.pages.awarness', compact('awarness1','awarness2','awarness3','awarness4','awarness5'));
    }
    public function fraud(): View {

		$fraud = CustomizeablePage::with('translation')->whereSlug('against-fraud')->whereStatus(true)->first();

        return view('frontend.pages.frawd', compact('fraud'));
    }
    public function depositRates(): View {
		
		$depositRates = CustomizeablePage::with('translation')->whereSlug('deposit-rates')->whereStatus(true)->first();

        return view('frontend.pages.deposit-rates', compact('depositRates'));

    }
    public function lendingRates(): View {
		
		$lendingRates = CustomizeablePage::with('translation')->whereSlug('lending-rates')->whereStatus(true)->first();

        return view('frontend.pages.lending-rates', compact('lendingRates'));

    }
    public function debtManagement(): View {
		
		$debtManagement1 = CustomizeablePage::with('translation')->whereSlug('debt-management-1')->whereStatus(true)->first();
		$debtManagement2 = CustomizeablePage::with('translation')->whereSlug('debt-management-2')->whereStatus(true)->first();

        return view('frontend.pages.debt-management', compact('debtManagement1','debtManagement2'));

    }
	public function faq(): View {
        $faqs = Faq::select('id')->with(['translation' => function ($query) {
            $query->select('faq_id', 'question', 'answer');
        }])->active()->latest()->get();

        return view('frontend.pages.faq', compact('faqs'));

    }
    public function pricing(): View {
        /*$per_age = cache('CustomPagination')?->pricing_plan ?? CustomPagination::where('section_name', 'Pricing Plan')->value('item_qty');

        $plans = SubscriptionPlan::select('id', 'plan_price','expiration_date','button_url')->with([
            'translation'          => function ($query) {
                $query->select( 'subscription_plan_id','plan_name','short_description','description','button_text');
            },
        ])->active()->orderBy('serial')->paginate($per_age);

        $faqs = Faq::select('id')->with(['translation' => function ($query) {
            $query->select('faq_id', 'question', 'answer');
        }])->active()->latest()->get();*/
		$atm = CustomizeablePage::with('translation')->whereSlug('atm-branches')->whereStatus(true)->first();

        return view('frontend.pages.pricing', compact('atm'));

    }
    public function atmOman(): View {
		$atm = CustomizeablePage::with('translation')->whereSlug('atm-branches-in-oman')->whereStatus(true)->first();

        return view('frontend.pages.atm-oman', compact('atm'));

    }
    public function atmQatar(): View {
		$atm = CustomizeablePage::with('translation')->whereSlug('atm-branches-in-qatar')->whereStatus(true)->first();

        return view('frontend.pages.atm-oman', compact('atm'));

    }
    public function team(): View {
        $per_age = cache('CustomPagination')?->team_list ?? CustomPagination::where('section_name', 'Team List')->value('item_qty');
        $teams = OurTeam::select('name', 'slug', 'designation', 'image')->active()->latest()->paginate($per_age);

        $theme_name = DEFAULT_HOMEPAGE;

        $testimonialSection = Section::whereHas("home", function ($q) use ($theme_name) {
            $q->where('slug', $theme_name);
        })->where('name', 'testimonial_section')->first();

        $testimonials = Testimonial::select('id')->with(['translation' => function ($query) {
            $query->select('testimonial_id', 'name', 'designation', 'comment');
        }])->active()->latest()->get();

        return view('frontend.pages.team', compact('teams', 'testimonialSection', 'testimonials'));
    }
    public function singleTeam($slug): View {
        $team = OurTeam::select('name', 'slug', 'designation', 'image', 'sort_description', 'email', 'phone', 'facebook', 'twitter', 'dribbble', 'instagram')->whereSlug($slug)->active()->first();
        if ($team) {
            return view('frontend.pages.team-details', compact('team'));
        }
        abort(404);
    }
    public function portfolios(): View {
        $per_age = cache('CustomPagination')?->portfolio_list ?? CustomPagination::where('section_name', 'Portfolio List')->value('item_qty');
        
        $projects = Project::select('id', 'slug', 'image')->with(['translation' => function ($query) {
            $query->select('project_id', 'title', 'project_category');
        }])->whereHas('service', function ($query) {
            $query->active();
        })->active()->latest()->paginate($per_age);
        

        return view('frontend.pages.portfolio.index', compact('projects'));
    }
    public function singlePortfolio($slug): View {
        $project = Project::select('id', 'slug', 'image','tags','created_at')->with([
            'translation' => function ($query) {
            $query->select('project_id', 'title','description','seo_title', 'seo_description');
        }])->active()->where('slug', $slug)->first();

        if (!$project) {
            abort(404);
        }


        return view('frontend.pages.portfolio.details', compact('project'));
    }
    public function services(): View {
        $per_age = cache('CustomPagination')?->service_list ?? CustomPagination::where('section_name', 'Service List')->value('item_qty');
        
        $services = Service::select('id', 'slug', 'icon')->with(['translation' => function ($query) {
            $query->select('service_id', 'title', 'short_description', 'description');
        }])->active()->latest()->paginate($per_age);
		
		$teller = Service::findBySlug("teller-services");
		$postdated = Service::findBySlug("postdated");
		//$iccs = Service::findBySlug("iccs");
		$iccs = Service::select('id', 'slug', 'icon', 'image')->with(['translation' => function ($query) {
            $query->select('service_id', 'title', 'short_description', 'description');
        }])->active()->where('slug', 'iccs')->first();
		$chequebook = Service::findBySlug("chequebook");
		//$dds = Service::findBySlug("dds");
		$dds = Service::select('id', 'slug', 'icon', 'image')->with(['translation' => function ($query) {
            $query->select('service_id', 'title', 'short_description', 'description');
        }])->active()->where('slug', 'dds')->first();
		$wps = Service::findBySlug("wps");
		$fts = Service::findBySlug("fts");
		$servicetext = CustomizeablePage::with('translation')->whereSlug('service')->whereStatus(true)->first();


        $theme_name = DEFAULT_HOMEPAGE;

        $bannerSection = Section::whereHas("home", function ($q) use ($theme_name) {
            $q->where('slug', $theme_name);
        })->where('name', 'banner_section')->first();
        
        return view('frontend.pages.service.index', compact('services','bannerSection','teller','postdated','iccs','chequebook','dds','wps','fts','servicetext'));
    }
    public function singleService($slug): View {
        $service = Service::select('id', 'slug', 'image','created_at')->with([
            'translation' => function ($query) {
            $query->select('service_id', 'title','description','seo_title', 'seo_description');
        }])->active()->where('slug', $slug)->first();

        if (!$service) {
            abort(404);
        }


        return view('frontend.pages.service.details', compact('service'));
    }
    public function contactTeamMember(Request $request, $slug):JsonResponse {
        try {
            $setting = cache()->get('setting');

            if ($setting?->contact_team_member !== 'active') {
                return response()->json(['success' => false, 'message' => __('Something went wrong, please try again')]);
            }

            $validator = Validator::make($request->all(), [
                'name'                 => 'required',
                'email'                => 'required',
                'message'              => 'required',
                'g-recaptcha-response' => $setting?->recaptcha_status == 'active' ? ['required', new CustomRecaptcha()] : '',
            ], [
                'name.required'                 => __('Name is required'),
                'email.required'                => __('Email is required'),
                'message.required'              => __('Message is required'),
                'g-recaptcha-response.required' => __('Please complete the recaptcha to submit the form'),
            ]);
            if ($validator->fails()) {
                return response()->json(['status' => false, 'message' => $validator->errors()], 422);
            }

            $member = OurTeam::select('email')->active()->whereSlug($slug)->first();
            if (!$member) {
                return response()->json(['success' => false, 'message' => __('Not Found!')], 404);
            }
            $str_replace = [
                'name'    => $request->name,
                'email'   => $request->email,
                'message' => $request->message,
            ];
            [$subject, $message] = $this->fetchEmailTemplate('contact_team_mail', $str_replace);
            $this->sendMail($member?->email, $subject, $message);
            return response()->json(['success' => true,'message' => __('Message Sent Successfully')]);
        } catch (\Exception $e) {
            info($e->getMessage());
            return response()->json(['success' => false,'message' => __('Mail sending operation failed. Please try again.')]);
        }
    }
    public function privacyPolicy(): View {
        $customPage = CustomizeablePage::with('translation')->whereSlug('privacy-policy')->whereStatus(true)->first();
        if ($customPage) {
            return view('frontend.pages.custom-page', compact('customPage'));
        }
        abort(404);
    }

    public function termsCondition(): View {
        $customPage = CustomizeablePage::with('translation')->whereSlug('terms-conditions')->whereStatus(true)->first();
        if ($customPage) {
            return view('frontend.pages.custom-page', compact('customPage'));
        }
        abort(404);
    }
    public function customPage($slug): View {
        $customPage = CustomizeablePage::with('translation')->whereStatus(true)->whereSlug($slug)->first();
        if ($customPage) {
            return view('frontend.pages.custom-page', compact('customPage'));
        }
        abort(404);
    }
}
