<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;

class ApiService
{
    protected $baseUrl;

    public function __construct()
    {
        $this->baseUrl = rtrim(env('API_URL', '/'));
    }

    public function fetchData($url, $token = null)
    {
        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . ($token ?: Session::get('token', '')),
            ])->get($this->baseUrl . $url);

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

    public function logout($token = null)
    {
        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . ($token ?: Session::get('token', '')),
            ])->get($this->baseUrl . '/logout');

            if ($response->successful()) {
                Session::forget('token');
                Session::flash('success', 'Logged out successfully.');
                return true;
            } else {
                $this->handleError($response);
                return false;
            }
        } catch (\Exception $e) {
            Log::error('Logout Error: ' . $e->getMessage());
            Session::flash('error', 'Logout failed: ' . $e->getMessage());
            return false;
        }
    }

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

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

    // public function get($url, $params = [])
    // {
    //     $token = $this->cookieService->getCookie()['token'] ?? null;
    //     $this->defaultHeaders['Authorization'] = 'Bearer ' . $token;
    //     return $this->makeRequest('get', $url, $params);
    // }

//     public function post($url, $params = [])
// {
//     return $this->makeRequest('post', $url, $params);
// }

public function get(string $endpoint, array $query = [])
{
    return Http::get("{$this->baseUrl}/{$endpoint}", $data);
}

public function post(string $endpoint, array $data = [])
{
    return Http::post("{$this->baseUrl}/{$endpoint}", $data);
}

    public function put($url, $params = [])
    {
        return $this->makeRequest('put', $url, $params);
    }

    public function delete($url, $params = [])
    {
        return $this->makeRequest('delete', $url, ['params' => $params]);
    }

    public function postMultipart($url, $data)
{
    return $this->makeRequest('postMultipart', $url, $data);
}
}