<?php

namespace App\Http\Controllers\Api;

use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SubscriptionController
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $subscription = Subscription::all();
        // Return as JSON response with UTF-8 encoding
        return response()->json($subscription, 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // Get the id_categoria and id_usuarios from the request body
        $id_categoria = $request->input('id_categoria');
        $id_usuario = $request->input('id_usuarios');

        // Validate the inputs
        if (!$id_categoria || !$id_usuario) {
            return response()->json(['message' => 'Both id_categoria and id_usuarios are required'], 400);
        }

        // Check if a subscription with the same id_usuarios and id_categorias already exists
        $existing_subscription = DB::table('subscriptions')
            ->where('id_categorias', $id_categoria)
            ->where('id_usuarios', $id_usuario)
            ->first();

        if ($existing_subscription) {
            return response()->json(['message' => 'Subscription already exists'], 409); // Conflict error
        }

        // Insert the new subscription into the database
        try {
            DB::table('subscriptions')->insert([
                'id_categorias' => $id_categoria,
                'id_usuarios' => $id_usuario,
            ]);

            return response()->json(['message' => 'Subscription created successfully'], 201); // Success (Created)
        } catch (\Exception $e) {
            // Handle any errors that occur during the insert
            return response()->json(['message' => 'Failed to create subscription', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        // Get categories where id_usuarios matches the given ID
        $subscription = Subscription::where('id_usuarios', $id)->get();

        return response()->json($subscription, 200,['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request)
    {
        // Get the id_categoria and id_usuarios from the request body
        $id_categoria = $request->input('id_categoria');
        $id_usuario = $request->input('id_usuarios'); 

        if (!$id_categoria || !$id_usuario) {
            return response()->json(['message' => 'Both id_categoria and id_usuarios are required'], 400);
        }
    
        // Use raw query to delete the subscription based on both keys
        $deleted = DB::table('subscriptions')
            ->where('id_categorias', $id_categoria)
            ->where('id_usuarios', $id_usuario)
            ->delete();
    
        if ($deleted) {
            return response()->json(['message' => 'Subscription deleted successfully'], 200);
        } else {
            return response()->json(['message' => 'Subscription not found or failed to delete'], 404);
        }
    }
}
