<?php

namespace App\Http\Controllers;

use App\Models\Service;
use Illuminate\Http\Request;

class PackageBuilderController extends Controller
{
public function buildpackage()
{
    $services = Service::active()->ordered()->get();
    $selectedServices = session('selected_services', []);
    $totalPrice = session('total_price', 0);
    
    return view('frontend.buildpackage', compact('services', 'selectedServices', 'totalPrice'));
}

public function addService(Request $request)
{
    $serviceId = $request->input('service_id');
    $service = Service::findOrFail($serviceId);
    
    $selectedServices = session('selected_services', []);
    $selectedServices = session('packge_type', 'Custom Package');
    
    if (!array_key_exists($serviceId, $selectedServices)) {
        $selectedServices[$serviceId] = [
            'id' => $service->id,
            'name' => $service->name,
            'price' => $service->price,
            'description' => $service->description,
            'quantity' => 1
        ];
        
        session(['selected_services' => $selectedServices]);
        $this->updateTotalPrice();
    }
    
    return redirect()->back()->with('success', 'Service added to package!');
}

public function removeService(Request $request)
{
    $serviceId = $request->input('service_id');
    $selectedServices = session('selected_services', []);
    
    if (array_key_exists($serviceId, $selectedServices)) {
        unset($selectedServices[$serviceId]);
        session(['selected_services' => $selectedServices]);
        $this->updateTotalPrice();
    }
    
    return redirect()->back()->with('success', 'Service removed from package!');
}

public function saveCustomPackage()
{
    $selectedServices = session('selected_services', []);
    $totalPrice = session('total_price', 0);
    
    if (empty($selectedServices)) {
        return redirect()->back()->with('error', 'Please add at least one service to create a package.');
    }
    
    // Store custom package info in session
    session([
        'package' => [
            'type' => 'custom',
            'name' => 'Custom Package',
            'price' => $totalPrice,
            'description' => 'Custom package with selected services',
            'services' => array_values($selectedServices)
        ]
    ]);
    
    // Clear temporary session data
    session()->forget(['selected_services', 'total_price']);
    
    return redirect()->route('request.services.contact')->with('success', 'Custom package created successfully!');
}

private function updateTotalPrice()
{
    $selectedServices = session('selected_services', []);
    $totalPrice = 0;
    
    foreach ($selectedServices as $service) {
        $totalPrice += $service['price'] * $service['quantity'];
    }
    
    session(['total_price' => $totalPrice]);
}
}