<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Services\ApiService;

class TailorController extends Controller
{
    /**
     * API Service
     *
     * @var ApiService
     */
    protected $apiService;

    /**
     * Constructor
     *
     * @param ApiService $apiService
     */
    public function __construct(ApiService $apiService)
    {
        $this->apiService = $apiService;
    }

    public function index()
    {
        try {
            $token = session('api_token');
            $tokenType = session('token_type');

            if (!$token || !$tokenType) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            // Debug log untuk token
            \Log::info('Token Info:', [
                'token' => $token,
                'type' => $tokenType
            ]);

            $response = $this->apiService->get('api/tailors/all');

            \Log::info('Tailors API Response', [
                'status' => $response->status(),
                'body' => $response->json()
            ]);

            if ($response->successful()) {
                $data = $response->json();
                if ($data['status'] === 'success' && isset($data['data'])) {
                    $tailors = $data['data'];
                    return view('admin.tailors.index', compact('tailors'));
                }
            }

            if ($response->status() === 401) {
                // Debug log untuk unauthorized
                \Log::warning('Unauthorized Access:', [
                    'headers' => $response->headers(),
                    'body' => $response->json()
                ]);
                
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $errorMessage = $response->json()['message'] ?? 'Unknown error';
            \Log::error('Tailor Index Error:', [
                'status' => $response->status(),
                'message' => $errorMessage,
                'headers' => $response->headers()
            ]);
            
            return back()->with('error', 'Gagal memuat data penjahit: ' . $errorMessage);
        } catch (\Exception $e) {
            \Log::error('Tailor Index Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return back()->with('error', 'Terjadi kesalahan saat memuat data penjahit');
        }
    }

    public function create()
    {
        return view('admin.tailors.create');
    }

    public function store(Request $request)
    {
        try {
            $token = session('api_token');
            $tokenType = session('token_type');

            if (!$token || !$tokenType) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $response = $this->apiService->post('api/users/tailors', $request->all());

            if ($response->successful()) {
                return redirect()->route('admin.tailors.index')
                    ->with('success', 'Penjahit berhasil ditambahkan');
            }

            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $errorMessage = $response->json()['message'] ?? 'Unknown error';
            \Log::error('Tailor Store Error:', [
                'status' => $response->status(),
                'message' => $errorMessage,
                'request' => $request->all()
            ]);

            return back()->with('error', 'Gagal menambahkan penjahit: ' . $errorMessage);
        } catch (\Exception $e) {
            \Log::error('Tailor Store Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return back()->with('error', 'Terjadi kesalahan saat menambahkan penjahit');
        }
    }

    public function edit($id)
    {
        try {
            $token = session('api_token');
            $tokenType = session('token_type');

            if (!$token || !$tokenType) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $response = $this->apiService->get("api/users/tailors/{$id}");

            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['data'])) {
                    $tailor = $data['data'];
                    return view('admin.tailors.edit', compact('tailor'));
                }
            }

            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $errorMessage = $response->json()['message'] ?? 'Unknown error';
            \Log::error('Tailor Edit Error:', [
                'status' => $response->status(),
                'message' => $errorMessage,
                'id' => $id
            ]);

            return back()->with('error', 'Gagal memuat data penjahit: ' . $errorMessage);
        } catch (\Exception $e) {
            \Log::error('Tailor Edit Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return back()->with('error', 'Terjadi kesalahan saat memuat data penjahit');
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $token = session('api_token');
            $tokenType = session('token_type');

            if (!$token || !$tokenType) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $response = $this->apiService->put("api/users/tailors/{$id}", $request->all());

            if ($response->successful()) {
                return redirect()->route('admin.tailors.index')
                    ->with('success', 'Data penjahit berhasil diperbarui');
            }

            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $errorMessage = $response->json()['message'] ?? 'Unknown error';
            \Log::error('Tailor Update Error:', [
                'status' => $response->status(),
                'message' => $errorMessage,
                'id' => $id,
                'request' => $request->all()
            ]);

            return back()->with('error', 'Gagal memperbarui data penjahit: ' . $errorMessage);
        } catch (\Exception $e) {
            \Log::error('Tailor Update Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return back()->with('error', 'Terjadi kesalahan saat memperbarui data penjahit');
        }
    }

    public function destroy($id)
    {
        try {
            $token = session('api_token');
            $tokenType = session('token_type');

            if (!$token || !$tokenType) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $response = $this->apiService->delete("api/users/tailors/{$id}");

            if ($response->successful()) {
                return redirect()->route('admin.tailors.index')
                    ->with('success', 'Penjahit berhasil dihapus');
            }

            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }

            $errorMessage = $response->json()['message'] ?? 'Unknown error';
            \Log::error('Tailor Destroy Error:', [
                'status' => $response->status(),
                'message' => $errorMessage,
                'id' => $id
            ]);

            return back()->with('error', 'Gagal menghapus penjahit: ' . $errorMessage);
        } catch (\Exception $e) {
            \Log::error('Tailor Destroy Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return back()->with('error', 'Terjadi kesalahan saat menghapus penjahit');
        }
    }
} 