<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class ApiService
{
    /**
     * Base URL for API
     *
     * @var string
     */
    protected $baseUrl;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->baseUrl = config('api.url');
    }

    /**
     * Get full API URL
     *
     * @param string $path
     * @return string
     */
    public function url($path = '')
    {
        // Remove leading slash if present
        $path = ltrim($path, '/');
        
        // API URL yang benar adalah https://api.tailors.stuffly.my.id/api/admin/login
        // Format yang benar adalah dengan menambahkan 'api/' di depan path
        
        // Handle base URL with or without trailing slash
        $baseUrl = rtrim($this->baseUrl, '/');
        
        // Tambahkan prefiks 'api/' jika belum ada
        if (strpos($path, 'api/') !== 0) {
            $path = "api/{$path}";
        }
        
        return "{$baseUrl}/{$path}";
    }
    
    /**
     * Get Http client with authorization headers
     *
     * @return \Illuminate\Http\Client\PendingRequest
     */
    public function http()
    {
        $token = session('api_token');
        $tokenType = session('token_type');
        
        return Http::withHeaders([
            'Authorization' => $token && $tokenType ? "{$tokenType} {$token}" : '',
            'Accept' => 'application/json',
        ])->withOptions([
            'verify' => false, // Disable SSL verification for development
        ]);
    }
    
    /**
     * Perform GET request
     *
     * @param string $path
     * @param array $params
     * @return \Illuminate\Http\Client\Response
     */
    public function get($path, array $params = [])
    {
        $url = $this->url($path);
        \Log::debug("API GET Request", [
            'url' => $url,
            'params' => $params
        ]);
        
        $response = $this->http()->get($url, $params);
        
        \Log::debug("API GET Response", [
            'status' => $response->status(),
            'body' => $response->json()
        ]);
        
        return $response;
    }
    
    /**
     * Perform POST request
     *
     * @param string $path
     * @param array $data
     * @param array $files
     * @return \Illuminate\Http\Client\Response
     */
    public function post($path, array $data = [], array $files = [])
    {
        $url = $this->url($path);
        \Log::debug("API POST Request", [
            'url' => $url,
            'data' => $data
        ]);
        
        // Jika ada file, gunakan multipart/form-data
        if (!empty($files)) {
            $response = $this->httpMultipart($files)->post($url, $data);
        } else {
            $response = $this->http()->post($url, $data);
        }
        
        \Log::debug("API POST Response", [
            'status' => $response->status(),
            'body' => $response->json()
        ]);
        
        return $response;
    }
    
    /**
     * Get Http client with headers for multipart/form-data (file uploads)
     *
     * @return \Illuminate\Http\Client\PendingRequest
     */
    protected function httpMultipart($files = [])
    {
        $token = session('api_token');
        $tokenType = session('token_type');
        
        $client = Http::withHeaders([
            'Authorization' => $token && $tokenType ? "{$tokenType} {$token}" : '',
            'Accept' => 'application/json',
        ])->withOptions([
            'verify' => false, // Disable SSL verification for development
        ]);
        
        // Tambahkan file ke request
        foreach ($files as $name => $file) {
            $client = $client->attach($name, file_get_contents($file->path()), $file->getClientOriginalName());
        }
        
        return $client;
    }
    
    /**
     * Perform PUT request
     *
     * @param string $path
     * @param array $data
     * @return \Illuminate\Http\Client\Response
     */
    public function put($path, array $data = [])
    {
        return $this->http()->put($this->url($path), $data);
    }
    
    /**
     * Perform DELETE request
     *
     * @param string $path
     * @param array $params
     * @return \Illuminate\Http\Client\Response
     */
    public function delete($path, array $params = [])
    {
        return $this->http()->delete($this->url($path), $params);
    }
} 