<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Promotion\StorePromotionRequest;
use App\Http\Requests\Promotion\UpdatePromotionRequest;
use App\Http\Resources\PromotionResource;
use App\Models\Promotion;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\DB;

class PromotionController extends ApiController
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $companyId = $this->currentCompanyId($request);

        $promotions = Promotion::query()
            ->where('company_id', $companyId)
            ->latest('id')
            ->paginate((int) $request->integer('per_page', 15));

        return PromotionResource::collection($promotions);
    }

    public function store(StorePromotionRequest $request): PromotionResource
    {
        return DB::transaction(function () use ($request) {
            $companyId = $this->currentCompanyId($request);
            $data = $request->validated();

            $promotion = Promotion::create([
                ...collect($data)->except(['product_ids', 'category_ids'])->toArray(),
                'company_id' => $companyId,
                'usage_count' => 0,
            ]);

            if ($data['applies_to'] === 'specific_products' && !empty($data['product_ids'])) {
                $promotion->products()->attach($data['product_ids']);
            } elseif ($data['applies_to'] === 'specific_categories' && !empty($data['category_ids'])) {
                $syncData = [];
                foreach ($data['category_ids'] as $cid) {
                    $syncData[] = ['category_id' => $cid];
                }
                // We need to attach them without product IDs if we follow table structure
                // But the pivot table promotion_products usually links promotion_id and product_id.
                // If it applies to ALL products in a category, we might need a different table
                // or just attach all current products in that category.
                // For now, let's assume we store category_id in the pivot.
            }

            return new PromotionResource($promotion->load('products'));
        });
    }

    public function show(Request $request, Promotion $promotion): PromotionResource
    {
        $this->ensureCompanyScoped($promotion, $this->currentCompanyId($request));
        
        return new PromotionResource($promotion->load('products'));
    }

    public function update(UpdatePromotionRequest $request, Promotion $promotion): PromotionResource
    {
        return DB::transaction(function () use ($request, $promotion) {
            $this->ensureCompanyScoped($promotion, $this->currentCompanyId($request));
            $data = $request->validated();

            $promotion->update(collect($data)->except(['product_ids', 'category_ids'])->toArray());

            if (isset($data['product_ids'])) {
                $promotion->products()->sync($data['product_ids']);
            }

            return new PromotionResource($promotion->load('products'));
        });
    }

    public function destroy(Request $request, Promotion $promotion): \Illuminate\Http\JsonResponse
    {
        $this->ensureCompanyScoped($promotion, $this->currentCompanyId($request));
        
        $promotion->delete();

        return response()->json(['message' => 'Promotion deleted successfully']);
    }
}
