<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\BusinessModel;
use App\Models\BusinessType;
use App\Models\Package;
use App\Models\ServiceRequest;
use App\Models\State;
use Illuminate\Http\Request;

class RequestServicesController extends Controller
{
    public function contact()
    {
        $contactinfo = session('contact_info');
        return view('frontend.request_services.contact', compact('contactinfo'));
    }


    public function contactDataStore(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email',
            'company' => 'nullable|string|max:255',
            'phone' => 'nullable|string',
            'full_phone' => 'nullable|string',
        ]);
        session(['contact_info' => $validated]);
        return redirect()->route('request.services.bussinessType')->with('success', 'Contact information saved successfully.');
    }


    public function bussinessType()
    {
        $businessType = BusinessType::active()->ordered()->get();

        return view('frontend.request_services.businessType', compact('businessType'));
    }


    public function storeBusinessType(Request $request)
    {
        $validated = $request->validate([
            'business_type' => 'required|exists:business_types,id'
        ]);
        session(['business_type' => $validated['business_type']]);
        return redirect()->route('business.model')->with('success', 'Business type saved successfully.');
    }


    public function bussinessModel()
    {
        $businessModel = BusinessModel::active()->ordered()->get();
        return view('frontend.request_services.bussinessModel', compact('businessModel'));
    }


    public function storeBusinessModel(Request $request)
    {
        $validated = $request->validate([
            'business_model' => 'required|exists:business_models,id'
        ]);
        session(['business_model' => $validated['business_model']]);
        return redirect()->route('business.branch')->with('success', 'Business model saved successfully.');
    }



    public function branch()
    {
        $branches = Branch::latest()->get();
        return view('frontend.request_services.branch', compact('branches'));
    }

    public function storeBranch(Request $request)
    {
        $validated = $request->validate([
            'branch' => 'required|exists:branches,id'
        ]);

        session(['branch' => $validated['branch']]);

        return redirect()->route('business.overview')->with('success', 'Branch saved successfully.');
    }


    public function pre_packages(Request $request)
    {

        session(['packge_type' => 'prebuilt']);
        session(['packge__id' => $request->id]);

        session()->forget('selected_services');
        session()->forget('total_price');

        return redirect()->route('request.services.contact');
    }




    public function overview()
    {
        $packageType = session('packge_type');
        $packageData = session('selected_services', []);
        $totalPrice = session('total_price', 0);

        $packageId = session()->get('packge__id');
        $packageTypeSession = session()->get('packge_type');

        $package = Package::find($packageId);

        $branchId = session('branch');
        $branch = $branchId ? Branch::find($branchId) : null;

        // Prebuilt Package
        if ($packageTypeSession === 'prebuilt' && $packageId) {
            if ($package) {
                // Features may be JSON string or array, handle safely
                $features = $package->features;

                if (is_string($features)) {
                    $features = json_decode($features, true);
                }

                if (!is_array($features)) {
                    $features = [];
                }

                // Convert feature names into formatted data
                $packageData = collect($features)->map(function ($feature) {
                    return [
                        'id' => null,
                        'name' => $feature,
                        'price' => null,
                        'description' => null,
                    ];
                })->toArray();

                // Determine total price
                $totalPrice = $package->final_price ?? $package->price;

                return view('frontend.request_services.overview', compact(
                    'packageType',
                    'packageData',
                    'totalPrice',
                    'package',
                    'branch'
                ));
            }
        }

        // Get branch information from session


        // If it's custom package or no prebuilt data
        return view('frontend.request_services.overview', compact(
            'packageType',
            'packageData',
            'totalPrice',
            'package',
            'branch'
        ));
    }





    public function submitBusiness()
    {
        $user = auth()->user();

        if (!$user) {
            return redirect()->route('login')->with('error', 'You need to be logged in to submit a business request.');
        }

        $packageType = session('packge_type');
        $packageData = session('selected_services', []);
        $totalPrice = session('total_price', 0);

        $packageId = session()->get('packge__id');
        $packageTypeSession = session()->get('packge_type');

        $package = Package::find($packageId);
        if ($packageTypeSession === 'prebuilt' && $packageId) {

            if ($package) {
                $features = $package->features;

                if (is_string($features)) {
                    $features = json_decode($features, true);
                }

                if (!is_array($features)) {
                    $features = [];
                }
                $packageData = collect($features)->map(function ($feature) {
                    return [
                        'id' => null,
                        'name' => $feature,
                        'price' => null,
                        'description' => null,
                    ];
                })->toArray();
                $totalPrice = $package->final_price ?? $package->price;
            }
        }


        $serviceRequest = new ServiceRequest();
        $serviceRequest->user_id = $user->id;
        $serviceRequest->contact_info = session('contact_info');
        $serviceRequest->business_type_id = session('business_type');
        $serviceRequest->business_model_id = session('business_model');
        $serviceRequest->branch_id = session('branch');
        $serviceRequest->package_type = $packageType;
        $serviceRequest->package_id = $packageId;
        $serviceRequest->services_data = $packageData;
        $serviceRequest->total_price = $totalPrice;
        $serviceRequest->status = 'pending';


        $serviceRequest->save();
        session()->forget([
            'contact_info',
            'business_type',
            'business_model',
            'branch',
            'packge_type',
            'packge__id',
            'selected_services',
            'total_price'
        ]);
        return view('frontend.request_services.submit_success', compact('serviceRequest'));
    }
}
