<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;
use App\Livewire\ErrorHandler;

class BaseApiService
{
    protected $baseUrl;
    protected $defaultHeaders = [];

    public function __construct(string $baseUrl)
    {
        $this->baseUrl = $baseUrl;
    }

    protected function makeRequest($method, $url, $params = [], $headers = [])
    {
        try {
            $fullHeaders = array_merge($this->defaultHeaders, $headers, [
                'Authorization' => 'Bearer ' . Session::get('token', ''),
            ]);

            $response = Http::withHeaders($fullHeaders)->{$method}($this->baseUrl . $url, $params);

            if ($response->successful()) {
                return $response->json();
            } else {
                $this->handleError($response);
                return null;
            }
        } catch (\Exception $e) {
            Log::error('API Request Error: ' . $e->getMessage());
            Session::flash('error', 'API request failed: ' . $e->getMessage());
            return null;
        }
    }

    protected function handleError($response)
    {
        $status = $response->status();

        if ($status === 401) {
            Session::forget('token');
            throw new \Exception('Session expired. Please login again.');
        } elseif ($status === 422) {
            throw new \Exception('Validation error: ' . ($response->body() ?: 'Unknown validation error'));
        } elseif ($status === 404) {
            throw new \Exception('API resource not found.');
        } else {
            throw new \Exception('API error: ' . ($response->body() ?: 'Unknown error'));
        }
    }

    public function postMultipart($url, $data)
{
    try {
        $headers = array_merge($this->defaultHeaders, [
            'Authorization' => 'Bearer ' . Session::get('token', ''),
            'Content-Type' => 'multipart/form-data',
        ]);

        $response = Http::withHeaders($headers)->asMultipart();

        foreach ($data as $key => $value) {
            if ($value instanceof \Illuminate\Http\UploadedFile) {
                $response = $response->attach($key, $value->get(), $value->getClientOriginalName());
            } else {
                $response = $response->attach($key, $value);
            }
        }

        $response = $response->post($this->baseUrl . $url);

        if ($response->successful()) {
            return $response->json();
        } else {
            $this->handleError($response);
            return null;
        }
    } catch (\Exception $e) {
        Log::error('Multipart API Request Error: ' . $e->getMessage());
        throw $e;
    }
}
}