<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\OfferCollection;
use App\Http\Resources\OfferResource;
use App\Models\Offer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use App\Models\Position;


class OfferController extends Controller
{
    public function index(Request $request)
    {
        $perPage = (int) $request->get('per_page', 20);
        $search  = trim((string) $request->get('search', ''));

        $query = Offer::query()->with('positions')->latest();

        // Optional simple search if your offers table has "name" or "title"
        if ($search !== '') {
            $cols = Schema::getColumnListing('offers');
            $searchCols = array_values(array_intersect($cols, ['name', 'title', 'customer_name', 'client_name']));
            if (!empty($searchCols)) {
                $query->where(function ($q) use ($searchCols, $search) {
                    foreach ($searchCols as $col) {
                        $q->orWhere($col, 'like', "%{$search}%");
                    }
                });
            }
        }

        return new OfferCollection($query->paginate($perPage));
    }

    public function show(Offer $offer)
    {
        $offer->load('positions');
        return new OfferResource($offer);
    }

    /**
     * Expects:
     *  {
     *    "offer": { ...offer columns... },
     *    "positions": [ { ...position columns... }, ... ]
     *  }
     */
   public function store(Request $request)
{
    $request->validate([
        'name' => ['required', 'string', 'max:255'],
        'description' => ['nullable', 'string'],
        'margin' => ['nullable', 'numeric'],
        'color' => ['nullable', 'string', 'max:255'],
        'profile_id' => ['nullable'],
        'iron_id' => ['nullable'],
    ]);

    $payload = $this->filterToTableColumns('offers', $request->all());
    $offer = Offer::create($payload);
    $offer->load('positions');

    return (new OfferResource($offer))->response()->setStatusCode(201);
}

public function update(Request $request, Offer $offer)
{
    $request->validate([
        'name' => ['sometimes', 'required', 'string', 'max:255'],
        'description' => ['nullable', 'string'],
        'margin' => ['nullable', 'numeric'],
        'color' => ['nullable', 'string', 'max:255'],
        'profile_id' => ['nullable'],
        'iron_id' => ['nullable'],
    ]);

    $payload = $this->filterToTableColumns('offers', $request->all());
    $offer->update($payload);
    $offer->load('positions');

    return new OfferResource($offer);
}




    public function destroy(Offer $offer)
    {
        return DB::transaction(function () use ($offer) {
            $offer->positions()->delete();
            $offer->delete();
            return response()->json(['message' => 'Offer deleted']);
        });
    }

    private function filterToTableColumns(string $table, array $data): array
    {
        if (!Schema::hasTable($table)) return $data;

        $columns = Schema::getColumnListing($table);
        $blocked = ['id', 'created_at', 'updated_at', 'deleted_at'];
        $columns = array_values(array_diff($columns, $blocked));

        return array_intersect_key($data, array_flip($columns));
    }
}
