@extends('layouts.app')

@section('title', 'API Documentation')

@section('content')
<div class="content-header row">
    <div class="content-header-left col-md-6 col-12 mb-2">
        <h3 class="content-header-title mb-0">WaTicket API Documentation</h3>
        <div class="row breadcrumbs-top">
            <div class="breadcrumb-wrapper col-12">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('api.tokens.index') }}">API Tokens</a></li>
                    <li class="breadcrumb-item active">Documentation</li>
                </ol>
            </div>
        </div>
    </div>
    <div class="content-header-right col-md-6 col-12">
        <a href="{{ route('api.tokens.index') }}" class="btn btn-primary float-right">
            <i class="feather icon-arrow-left"></i> Back to Tokens
        </a>
    </div>
</div>

<div class="content-body">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header" style="background-color: #fd810e;">
                    <h4 class="card-title text-white"><i class="feather icon-book"></i> Quick Start Guide</h4>
                </div>
                <div class="card-body">
                    <h5>1. Authentication</h5>
                    <p>All API requests must include these headers:</p>
                    <pre class="bg-dark text-white p-3 rounded"><code>Authorization: Bearer YOUR_API_TOKEN
X-Device-ID: YOUR_DEVICE_ID
Content-Type: application/json
Accept: application/json</code></pre>

                    @if($devices->count() > 0)
                    <div class="alert alert-info mt-3">
                        <strong><i class="feather icon-info"></i> Your Device IDs:</strong>
                        <ul class="mb-0 mt-2">
                            @foreach($devices as $device)
                            <li><strong>{{ $device->id }}</strong> - {{ $device->sender ?? 'Device ' . $device->id }} ({{ $device->status }})</li>
                            @endforeach
                        </ul>
                    </div>
                    @endif

                    <h5 class="mt-4">2. Base URL</h5>
                    <pre class="bg-dark text-white p-3 rounded"><code>{{ url('/api/waticket') }}</code></pre>
                </div>
            </div>
        </div>
    </div>

    <!-- API Endpoints -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">API Endpoints</h4>
                </div>
                <div class="card-body">
                    <!-- Create Ticket -->
                    <div class="mb-4">
                        <h5><span class="badge badge-success">POST</span> /api/waticket/tickets</h5>
                        <p class="text-muted">Create a new support ticket</p>
                        
                        <h6>Request Body:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>{
  "customer_phone": "1234567890",
  "customer_name": "John Doe",
  "customer_email": "john@example.com",
  "subject": "Order Support - Invoice #12345",
  "description": "Customer needs help with payment issue",
  "priority": "high",
  "category": "order_support",
  "external_reference": "POS-ORDER-12345"
}</code></pre>

                        <h6>Response (201 Created):</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>{
  "success": true,
  "message": "Ticket created successfully",
  "data": {
    "ticket_id": 42,
    "ticket_number": "TKT-2025110001",
    "status": "new",
    "priority": "high",
    "assigned_to": "Agent Name",
    "created_at": "2025-11-10T14:30:00Z"
  }
}</code></pre>

                        <h6>cURL Example:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>curl -X POST {{ url('/api/waticket/tickets') }} \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "X-Device-ID: {{ $devices->first()->id ?? 'YOUR_DEVICE_ID' }}" \
  -H "Content-Type: application/json" \
  -d '{
    "customer_phone": "1234567890",
    "customer_name": "John Doe",
    "subject": "Need Help",
    "description": "Issue description",
    "priority": "medium"
  }'</code></pre>
                    </div>

                    <hr>

                    <!-- Get Ticket -->
                    <div class="mb-4">
                        <h5><span class="badge badge-primary">GET</span> /api/waticket/tickets/{ticket_number}</h5>
                        <p class="text-muted">Retrieve ticket details</p>
                        
                        <h6>cURL Example:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>curl {{ url('/api/waticket/tickets/TKT-2025110001') }} \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "X-Device-ID: {{ $devices->first()->id ?? 'YOUR_DEVICE_ID' }}"</code></pre>

                        <h6>Response (200 OK):</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>{
  "success": true,
  "data": {
    "ticket_number": "TKT-2025110001",
    "customer_phone": "1234567890",
    "customer_name": "John Doe",
    "subject": "Order Support",
    "status": "open",
    "priority": "high",
    "assigned_to": "Agent Name",
    "messages_count": 3,
    "created_at": "2025-11-10T14:30:00Z"
  }
}</code></pre>
                    </div>

                    <hr>

                    <!-- List Tickets -->
                    <div class="mb-4">
                        <h5><span class="badge badge-primary">GET</span> /api/waticket/tickets</h5>
                        <p class="text-muted">List all tickets with optional filters</p>
                        
                        <h6>Query Parameters:</h6>
                        <ul>
                            <li><code>status</code> - Filter by status (new, open, pending, resolved, closed)</li>
                            <li><code>priority</code> - Filter by priority (low, medium, high, urgent)</li>
                            <li><code>external_reference</code> - Filter by your reference ID</li>
                            <li><code>customer_phone</code> - Filter by customer phone</li>
                            <li><code>limit</code> - Results per page (default: 20, max: 100)</li>
                            <li><code>page</code> - Page number</li>
                        </ul>

                        <h6>cURL Example:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>curl "{{ url('/api/waticket/tickets?status=open&priority=high&limit=10') }}" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "X-Device-ID: {{ $devices->first()->id ?? 'YOUR_DEVICE_ID' }}"</code></pre>
                    </div>

                    <hr>

                    <!-- Add Message -->
                    <div class="mb-4">
                        <h5><span class="badge badge-success">POST</span> /api/waticket/tickets/{ticket_number}/messages</h5>
                        <p class="text-muted">Add a message to a ticket</p>
                        
                        <h6>Request Body:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>{
  "message": "Order has been refunded. Refund ID: REF-98765",
  "sender_type": "agent"
}</code></pre>

                        <h6>cURL Example:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>curl -X POST {{ url('/api/waticket/tickets/TKT-2025110001/messages') }} \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "X-Device-ID: {{ $devices->first()->id ?? 'YOUR_DEVICE_ID' }}" \
  -H "Content-Type: application/json" \
  -d '{"message": "Update from system", "sender_type": "agent"}'</code></pre>
                    </div>

                    <hr>

                    <!-- Update Status -->
                    <div class="mb-4">
                        <h5><span class="badge badge-warning">PATCH</span> /api/waticket/tickets/{ticket_number}/status</h5>
                        <p class="text-muted">Update ticket status</p>
                        
                        <h6>Request Body:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>{
  "status": "resolved"
}</code></pre>

                        <h6>Valid Statuses:</h6>
                        <ul>
                            <li><code>new</code> - Just created</li>
                            <li><code>open</code> - Being worked on</li>
                            <li><code>pending</code> - Waiting for customer</li>
                            <li><code>resolved</code> - Issue fixed</li>
                            <li><code>closed</code> - Ticket closed</li>
                        </ul>

                        <h6>cURL Example:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>curl -X PATCH {{ url('/api/waticket/tickets/TKT-2025110001/status') }} \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "X-Device-ID: {{ $devices->first()->id ?? 'YOUR_DEVICE_ID' }}" \
  -H "Content-Type: application/json" \
  -d '{"status": "resolved"}'</code></pre>
                    </div>

                    <hr>

                    <!-- Statistics -->
                    <div class="mb-4">
                        <h5><span class="badge badge-primary">GET</span> /api/waticket/statistics</h5>
                        <p class="text-muted">Get support statistics</p>
                        
                        <h6>cURL Example:</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>curl {{ url('/api/waticket/statistics') }} \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "X-Device-ID: {{ $devices->first()->id ?? 'YOUR_DEVICE_ID' }}"</code></pre>

                        <h6>Response (200 OK):</h6>
                        <pre class="bg-dark text-white p-3 rounded"><code>{
  "success": true,
  "data": {
    "total": 145,
    "by_status": {
      "new": 12,
      "open": 23,
      "pending": 8,
      "resolved": 45,
      "closed": 57
    },
    "by_priority": {
      "low": 30,
      "medium": 60,
      "high": 40,
      "urgent": 15
    },
    "unassigned": 5,
    "agents": {
      "total": 8,
      "online": 5,
      "available": 4
    }
  }
}</code></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- PHP Integration Example -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"><i class="feather icon-code"></i> PHP Integration Example (Ultimate POS)</h4>
                </div>
                <div class="card-body">
                    <pre class="bg-dark text-white p-3 rounded" style="max-height: 500px; overflow-y: auto;"><code>&lt;?php
// WaTicket Integration Class for Ultimate POS

class WaTicketIntegration
{
    private $apiUrl = '{{ url('/api/waticket') }}';
    private $apiToken = 'YOUR_API_TOKEN_HERE';
    private $deviceId = {{ $devices->first()->id ?? 'YOUR_DEVICE_ID' }};

    /**
     * Create support ticket from POS
     */
    public function createTicket($order, $issue)
    {
        $data = [
            'customer_phone' => $order->customer_phone,
            'customer_name' => $order->customer_name,
            'customer_email' => $order->customer_email,
            'subject' => "Order Support - Invoice #{$order->invoice_number}",
            'description' => $issue,
            'priority' => 'medium',
            'category' => 'order_support',
            'external_reference' => "POS-ORDER-{$order->id}",
        ];

        $response = $this->makeRequest('POST', '/tickets', $data);

        if ($response['success']) {
            // Save ticket number to order
            $order->update(['support_ticket' => $response['data']['ticket_number']]);
            return $response['data'];
        }

        return false;
    }

    /**
     * Get ticket status
     */
    public function getTicketStatus($ticketNumber)
    {
        $response = $this->makeRequest('GET', "/tickets/{$ticketNumber}");
        return $response['success'] ? $response['data'] : null;
    }

    /**
     * Update ticket status
     */
    public function resolveTicket($ticketNumber)
    {
        $data = ['status' => 'resolved'];
        return $this->makeRequest('PATCH', "/tickets/{$ticketNumber}/status", $data);
    }

    /**
     * Add message to ticket
     */
    public function addMessage($ticketNumber, $message)
    {
        $data = [
            'message' => $message,
            'sender_type' => 'agent'
        ];
        return $this->makeRequest('POST', "/tickets/{$ticketNumber}/messages", $data);
    }

    /**
     * Make API request
     */
    private function makeRequest($method, $endpoint, $data = [])
    {
        $ch = curl_init($this->apiUrl . $endpoint);

        $headers = [
            'Authorization: Bearer ' . $this->apiToken,
            'X-Device-ID: ' . $this->deviceId,
            'Content-Type: application/json',
            'Accept: application/json',
        ];

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        } elseif ($method === 'PATCH') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return json_decode($response, true);
    }
}

// Usage Example
$waticket = new WaTicketIntegration();

// Create ticket when customer reports issue
$ticket = $waticket->createTicket($order, 'Payment was charged twice');
echo "Ticket created: " . $ticket['ticket_number'];

// Check status later
$status = $waticket->getTicketStatus('TKT-2025110001');
echo "Current status: " . $status['status'];

// Add update
$waticket->addMessage('TKT-2025110001', 'Refund has been processed');

// Resolve when done
$waticket->resolveTicket('TKT-2025110001');
?&gt;</code></pre>
                </div>
            </div>
        </div>
    </div>

    <!-- Error Handling -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"><i class="feather icon-alert-triangle"></i> Error Handling</h4>
                </div>
                <div class="card-body">
                    <h6>HTTP Status Codes:</h6>
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Code</th>
                                <th>Meaning</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><span class="badge badge-success">200</span></td>
                                <td>Success</td>
                                <td>Request completed successfully</td>
                            </tr>
                            <tr>
                                <td><span class="badge badge-success">201</span></td>
                                <td>Created</td>
                                <td>Resource created successfully</td>
                            </tr>
                            <tr>
                                <td><span class="badge badge-warning">400</span></td>
                                <td>Bad Request</td>
                                <td>Check request format and parameters</td>
                            </tr>
                            <tr>
                                <td><span class="badge badge-warning">401</span></td>
                                <td>Unauthorized</td>
                                <td>Check your API token</td>
                            </tr>
                            <tr>
                                <td><span class="badge badge-warning">403</span></td>
                                <td>Forbidden</td>
                                <td>Check device_id or permissions</td>
                            </tr>
                            <tr>
                                <td><span class="badge badge-warning">404</span></td>
                                <td>Not Found</td>
                                <td>Resource doesn't exist or wrong device_id</td>
                            </tr>
                            <tr>
                                <td><span class="badge badge-warning">422</span></td>
                                <td>Validation Error</td>
                                <td>Check required fields and formats</td>
                            </tr>
                            <tr>
                                <td><span class="badge badge-danger">500</span></td>
                                <td>Server Error</td>
                                <td>Contact support</td>
                            </tr>
                        </tbody>
                    </table>

                    <h6 class="mt-4">Error Response Format:</h6>
                    <pre class="bg-dark text-white p-3 rounded"><code>{
  "success": false,
  "message": "Error description",
  "errors": {
    "field_name": ["Validation error message"]
  }
}</code></pre>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
