<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Sanctum\PersonalAccessToken;

class ApiTokenController extends Controller
{
    /**
     * Display API token management page
     */
    public function index()
    {
        $user = Auth::user();
        $tokens = $user->tokens()->orderBy('created_at', 'desc')->get();
        
        // Get user's devices for the token form
        $devices = \App\Models\Device::where('user_id', $user->id)->get();

        return view('api.tokens.index', compact('tokens', 'devices'));
    }

    /**
     * Generate a new API token
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'abilities' => 'nullable|array',
        ]);

        $user = Auth::user();

        // Define abilities based on selection or default to all
        $abilities = $validated['abilities'] ?? ['*'];

        $token = $user->createToken(
            $validated['name'],
            $abilities
        );

        // Store the plain text token in session to display once
        session()->flash('new_token', $token->plainTextToken);

        return redirect()->route('api.tokens.index')
            ->with('success', 'API token created successfully. Please copy it now, it will not be shown again.');
    }

    /**
     * Revoke (delete) a token
     */
    public function destroy($id)
    {
        $user = Auth::user();
        
        $token = $user->tokens()->where('id', $id)->first();

        if (!$token) {
            return back()->with('error', 'Token not found.');
        }

        $token->delete();

        return back()->with('success', 'API token revoked successfully.');
    }

    /**
     * Get token details (for viewing abilities)
     */
    public function show($id)
    {
        $user = Auth::user();
        
        $token = $user->tokens()->where('id', $id)->first();

        if (!$token) {
            return response()->json(['error' => 'Token not found'], 404);
        }

        return response()->json([
            'name' => $token->name,
            'abilities' => $token->abilities,
            'created_at' => $token->created_at->format('Y-m-d H:i:s'),
            'last_used_at' => $token->last_used_at?->format('Y-m-d H:i:s'),
            'expires_at' => $token->expires_at?->format('Y-m-d H:i:s'),
        ]);
    }

    /**
     * Test API connection
     */
    public function test(Request $request)
    {
        $validated = $request->validate([
            'token' => 'required|string',
            'device_id' => 'required|integer',
        ]);

        // Make a test API call
        try {
            $ch = curl_init(url('/api/user'));
            
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Authorization: Bearer ' . $validated['token'],
                'Accept: application/json',
            ]);
            
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For local testing
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode === 200) {
                return response()->json([
                    'success' => true,
                    'message' => 'API token is valid and working!',
                    'user' => json_decode($response, true),
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'API token is invalid or expired.',
                    'http_code' => $httpCode,
                ], 401);
            }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to test API: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get API documentation
     */
    public function documentation()
    {
        $user = Auth::user();
        $devices = \App\Models\Device::where('user_id', $user->id)->get();
        
        return view('api.documentation', compact('devices'));
    }
}
