<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Business;
use App\Models\Contact;
use App\Support\ApiResponse;
use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function index(Request $request, int $businessId)
    {
        // The frontend uses /api/contacts/{id} for both business listing AND single contact.
        // If a Business with this id exists, return its contacts; otherwise treat as contactId.
        $business = Business::find($businessId);
        if ($business) {
            $query = Contact::where('business_id', $businessId)->where('is_active', true);
            if ($request->has('isSupplier')) {
                $val = filter_var($request->query('isSupplier'), FILTER_VALIDATE_BOOLEAN);
                $val ? $query->where('is_supplier', true) : $query->where('is_customer', true);
            }
            return ApiResponse::success('Contacts', $query->orderBy('name')->get());
        }

        $contact = Contact::find($businessId);
        if (!$contact) {
            return ApiResponse::error('Not found', null, 404);
        }
        return ApiResponse::success('Contact', $contact);
    }

    public function store(Request $request, ?int $businessId = null)
    {
        // The frontend sometimes POSTs to /api/contacts without a business id in
        // the URL and includes businessId in the body — handle either shape.
        $businessId = $businessId ?: (int) ($request->input('businessId') ?? $request->input('business_id') ?? 0);
        if (!$businessId) return ApiResponse::error('businessId is required', null, 422);

        $data = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email',
            'phone' => 'nullable|string',
            'address' => 'nullable|string',
            'taxNumber' => 'nullable|string',
            'isSupplier' => 'nullable|boolean',
            'isCustomer' => 'nullable|boolean',
            'id' => 'nullable|integer',
        ]);

        $payload = [
            'business_id' => $businessId,
            'name'        => $data['name'],
            'email'       => $data['email'] ?? null,
            'phone'       => $data['phone'] ?? null,
            'address'     => $data['address'] ?? null,
            'tax_number'  => $data['taxNumber'] ?? null,
            'is_supplier' => (bool) ($data['isSupplier'] ?? false),
            'is_customer' => !(bool) ($data['isSupplier'] ?? false),
        ];

        // Same endpoint handles create and update — the frontend Save() reuses POST.
        if (!empty($data['id'])) {
            $contact = Contact::where('business_id', $businessId)->findOrFail($data['id']);
            $contact->update($payload);
            return ApiResponse::success('Contact updated', $contact);
        }
        $contact = Contact::create($payload);
        return ApiResponse::success('Contact created', $contact);
    }

    public function update(Request $request, int $businessId, int $id)
    {
        $contact = Contact::where('business_id', $businessId)->findOrFail($id);
        $contact->update($request->only(['name', 'email', 'phone', 'address', 'tax_number', 'is_supplier', 'is_customer', 'is_active']));
        return ApiResponse::success('Contact updated', $contact);
    }

    public function destroy(Request $request, int $businessId, int $id)
    {
        $contact = Contact::where('business_id', $businessId)->findOrFail($id);
        $contact->is_active = false;
        $contact->save();
        return ApiResponse::success('Contact removed');
    }
}
