<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\SubscriptionPackage;
use App\Models\SubscriptionPackageProduct;

class SubscriptionController extends Controller
{

    // Show Create Page
    public function create()
    {
        return view('backend.subscription.create');
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $subscriptions = SubscriptionPackage::orderBy('id', 'DESC')->get();
        return view('backend.subscription.index')->with('subscriptions', $subscriptions);
    }


    public function update(Request $request, $id)
    {
        $subscription = SubscriptionPackage::findOrFail($id);

        $this->validate($request, [ 
            'package_name' => 'required|string|max:255',
            'package_description' => 'required|String',
            'price' => 'required|numeric',
            'duration_days' => 'required|numeric',
            'products' => 'required|array|min:1',
        ]);

        $subscription->update([
            'package_name' => $request->package_name,
            'package_description' => $request->package_description,
            'price' => $request->price,
            'duration_days' => $request->duration_days,
        ]);

        // Delete old products
        SubscriptionPackageProduct::where('subscription_id', $id)->delete();

        // Reinsert products
        foreach ($request->products as $product) {
            SubscriptionPackageProduct::create([
                'subscription_id' => $subscription->id,
                'product_name' => $product['product_name'],
                'product_description' => $product['product_description'] ?? null,
                'category' => $product['category'],
                'quantity' => $product['quantity'],
                'price' => $product['price'],
            ]);
        }

        request()->session()->flash('success', 'Subscription Successfully Updated');

        return redirect()->route('subscription.index');
    }
    /**
     * Show subscription details
     */
    public function show($id)
    {
        $subscription = SubscriptionPackage::findOrFail($id);
        $products = SubscriptionPackageProduct::where('subscription_id', $id)->get();

        return view('backend.subscription.show')
            ->with('subscription', $subscription)
            ->with('products', $products);
    }

    /**
     * Delete subscription
     */
    public function destroy($id)
    {
        $subscription = SubscriptionPackage::findOrFail($id);

        // Delete related products first
        SubscriptionPackageProduct::where('subscription_id', $id)->delete();

        $status = $subscription->delete();

        if ($status) {
            request()->session()->flash('success', 'Subscription Successfully Deleted');
        } else {
            request()->session()->flash('error', 'Error while deleting subscription');
        }

        return redirect()->route('subscription.index');
    }


    public function frontendSubscriptions()
    {
        $subscriptions = SubscriptionPackage::where('is_active', 1)
            ->orderBy('id', 'DESC')
            ->get();

        return view('frontend.pages.subscription')
            ->with('subscriptions', $subscriptions);
    }


    public function checkout(Request $request)
{
    $request->validate([
        'subscription_id' => 'required|exists:subscription_packages,id',
    ]);

    // Store selected subscription in session
    session([
        'checkout_subscription_id' => $request->subscription_id
    ]);

    // Redirect to checkout page
    return redirect()->route('checkout');
}

    public function edit($id)
    {
        $subscription = SubscriptionPackage::findOrFail($id);
        $products = SubscriptionPackageProduct::where('subscription_id', $id)->get();

        return view('backend.subscription.edit')
            ->with('subscription', $subscription)
            ->with('products', $products);
    }
    // Store Subscription Package
    public function store(Request $request)
    {
        $request->validate([
            'package_name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'duration_days' => 'required|integer|min:1',
            'package_description' => 'required|String',
            'products' => 'required|array|min:1',
            'products.*.product_name' => 'required|string|max:255',
            'products.*.category' => 'required',
            'products.*.quantity' => 'required|integer|min:1',
            'products.*.price' => 'required|numeric|min:0',
        ]);

        DB::beginTransaction();

        try {

            // Insert into subscription_packages
            $package = SubscriptionPackage::create([
                'package_name' => $request->package_name,
                'package_description' => $request->package_description,
                'price' => $request->price,
                'duration_days' => $request->duration_days,
                'is_active' => 1,
            ]);

            // Insert products
            foreach ($request->products as $product) {

                SubscriptionPackageProduct::create([
                    'subscription_id' => $package->id,
                    'product_name' => $product['product_name'],
                    'product_description' => $product['product_description'] ?? null,
                    'category' => $product['category'],
                    'quantity' => $product['quantity'],
                    'price' => $product['price'],
                ]);
            }

            DB::commit();

            return redirect()->back()->with('success', 'Subscription Package Created Successfully');
        } catch (\Exception $e) {

            DB::rollBack();

            return redirect()->back()->with('error', 'Something went wrong!');
        }
    }
}