<?php

namespace App\Http\Controllers;

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

class PixelController extends Controller
{
    // 1️⃣ Search for a specific platform or get all
    public function search(Request $request)
    {
        $request->validate([
            'platform' => 'nullable|in:google,facebook,snapchat,tiktok',
        ]);

        if ($request->has('platform')) {
            // Search by platform
            $pixel = Pixel::where('platform', $request->platform)->first();

            if ($pixel) {
                return response()->json($pixel, 200);
            }

            return response()->json(['message' => 'Platform not found'], 404);
        }

        // Get all platforms
        $pixels = Pixel::all();
        return response()->json($pixels, 200);
    }

    // 2️⃣ Store or update a pixel
    public function store(Request $request)
    {
        $request->validate([
            'platform' => 'required|in:google,facebook,snapchat,tiktok',
            'pixel_id' => 'array', // Optional, can be empty
            'pixel_id.*' => 'string|distinct', // Each pixel ID must be unique
            'conversion_type' => 'nullable|string',
        ]);

        $pixel = Pixel::updateOrCreate(
            ['platform' => $request->platform],
            [
                'pixel_id' => $request->pixel_id ?? [], // Set to empty array if null
                'conversion_type' => $request->conversion_type,
            ]
        );

        return response()->json($pixel, 200);
    }

    public function emptyPixel(Request $request)
    {
        $request->validate([
            'platform' => 'required|in:google,facebook,snapchat,tiktok',
        ]);

        $pixel = Pixel::where('platform', $request->platform)->first();

        if ($pixel) {
            $pixel->update(['pixel_id' => []]);
            return response()->json(['message' => 'Pixel IDs emptied successfully', 'data' => $pixel]);
        }

        return response()->json(['message' => 'Platform not found'], 404);
    }
}
