<?php

/**
 * Test script for Grievance Pagination API
 * 
 * This script helps you test the new pagination functionality
 * Run this in a Laravel tinker session or create a test route
 */

// Sample data creation for testing
function createSampleGrievances()
{
    $sampleGrievances = [
        [
            'voter_id' => 'V001',
            'ration_card_number' => 'RC123456',
            'title' => 'Ration card not received',
            'description' => 'Applied for ration card 3 months ago but still not received',
            'status' => 'OPEN',
            'reported_at' => now()->subDays(5),
            'target_resolve_by' => now()->addDays(10),
        ],
        [
            'voter_id' => 'V002', 
            'ration_card_number' => 'RC123456',
            'title' => 'Incorrect name on ration card',
            'description' => 'Name spelling is wrong on the ration card',
            'status' => 'IN_PROGRESS',
            'reported_at' => now()->subDays(3),
            'target_resolve_by' => now()->addDays(7),
        ],
        [
            'voter_id' => 'V003',
            'ration_card_number' => 'RC789012',
            'title' => 'Missing family member',
            'description' => 'Newly married daughter-in-law not added to ration card',
            'status' => 'OPEN',
            'reported_at' => now()->subDays(2),
            'target_resolve_by' => now()->addDays(15),
        ],
        [
            'voter_id' => 'V004',
            'ration_card_number' => 'RC456789',
            'title' => 'Ration shop quality issue',
            'description' => 'Poor quality rice being distributed',
            'status' => 'CLOSED',
            'reported_at' => now()->subDays(20),
            'target_resolve_by' => now()->subDays(5),
            'closed_at' => now()->subDays(2),
        ],
        [
            'voter_id' => 'V005',
            'ration_card_number' => 'RC123456',
            'title' => 'Ration shop timing issue',
            'description' => 'Shop opens very late, causing problems for working people',
            'status' => 'HOLD',
            'reported_at' => now()->subDays(1),
            'target_resolve_by' => now()->addDays(5),
        ],
    ];

    foreach ($sampleGrievances as $grievanceData) {
        \App\Models\Grievance::create($grievanceData);
    }

    return count($sampleGrievances);
}

// Test function to check pagination functionality
function testGrievancePagination()
{
    echo "=== Testing Grievance Pagination ===\n\n";
    
    // Initialize services
    $grievanceRepository = new \App\Repositories\GrievanceRepository();
    $response = new \App\ResponseHandler\Response();
    $grievanceService = new \App\Services\GrievanceService($grievanceRepository, $response);
    
    // Test 1: Get paginated grievances by ration card
    echo "Test 1: Search by Ration Card 'RC123456'\n";
    echo "----------------------------------------\n";
    $result1 = $grievanceService->getPaginatedGrievances('RC123456', 2, null);
    echo "Result: " . json_encode($result1->getData(), JSON_PRETTY_PRINT) . "\n\n";
    
    // Test 2: Get all paginated grievances with status filter
    echo "Test 2: Get all OPEN grievances (paginated)\n";
    echo "-------------------------------------------\n";
    $result2 = $grievanceService->getAllGrievancesPaginated('OPEN', 3);
    echo "Result: " . json_encode($result2->getData(), JSON_PRETTY_PRINT) . "\n\n";
    
    // Test 3: Get all paginated grievances without filter
    echo "Test 3: Get all grievances (no filter, paginated)\n";
    echo "------------------------------------------------\n";
    $result3 = $grievanceService->getAllGrievancesPaginated(null, 4);
    echo "Result: " . json_encode($result3->getData(), JSON_PRETTY_PRINT) . "\n\n";
}

// Test HTTP requests using Laravel's HTTP client
function testHttpRequests()
{
    echo "=== Testing HTTP Endpoints ===\n\n";
    
    $baseUrl = config('app.url', 'http://localhost:8000');
    
    // Test endpoints
    $endpoints = [
        [
            'name' => 'Search by Ration Card',
            'url' => $baseUrl . '/api/grievance/paginated?ration_card_number=RC123456&per_page=2&page=1',
            'method' => 'GET'
        ],
        [
            'name' => 'Get All Open Grievances',
            'url' => $baseUrl . '/api/grievance/paginated-all?status=OPEN&per_page=3&page=1',
            'method' => 'GET'
        ],
        [
            'name' => 'Get All Grievances (No Filter)',
            'url' => $baseUrl . '/api/grievance/paginated-all?per_page=5&page=1',
            'method' => 'GET'
        ]
    ];
    
    foreach ($endpoints as $endpoint) {
        echo "Testing: {$endpoint['name']}\n";
        echo "URL: {$endpoint['url']}\n";
        echo "Method: {$endpoint['method']}\n";
        
        try {
            $response = \Illuminate\Support\Facades\Http::get($endpoint['url']);
            echo "Status: " . $response->status() . "\n";
            echo "Response: " . json_encode($response->json(), JSON_PRETTY_PRINT) . "\n";
        } catch (Exception $e) {
            echo "Error: " . $e->getMessage() . "\n";
        }
        
        echo "\n" . str_repeat("-", 50) . "\n\n";
    }
}

/**
 * CURL Examples for testing from command line
 */
function getCurlExamples()
{
    $baseUrl = 'http://localhost:8000'; // Adjust your base URL
    
    return [
        'Search by Ration Card' => "curl -X GET \"{$baseUrl}/api/grievance/paginated?ration_card_number=RC123456&per_page=5&page=1\"",
        
        'Search with Status Filter' => "curl -X GET \"{$baseUrl}/api/grievance/paginated?ration_card_number=RC123456&status=OPEN&per_page=10&page=1\"",
        
        'Get All Open Grievances' => "curl -X GET \"{$baseUrl}/api/grievance/paginated-all?status=OPEN&per_page=15&page=1\"",
        
        'Get All Grievances' => "curl -X GET \"{$baseUrl}/api/grievance/paginated-all?per_page=20&page=1\"",
        
        'Create Sample Grievance' => "curl -X POST \"{$baseUrl}/api/grievance/create\" \\
            -H \"Content-Type: application/json\" \\
            -d '{
                \"voter_id\": \"V006\",
                \"ration_card_number\": \"RC999888\",
                \"title\": \"Test grievance for pagination\",
                \"description\": \"This is a test grievance to check pagination functionality\",
                \"status\": \"OPEN\",
                \"target_resolve_by\": \"2024-12-30\"
            }'"
    ];
}

// Usage instructions
echo "
====================================================
GRIEVANCE PAGINATION TESTING SCRIPT
====================================================

To use this script, you have several options:

1. CREATE SAMPLE DATA:
   \$count = createSampleGrievances();
   echo \"Created \$count sample grievances\";

2. TEST PAGINATION FUNCTIONALITY:
   testGrievancePagination();

3. TEST HTTP ENDPOINTS:
   testHttpRequests();

4. GET CURL EXAMPLES:
   \$examples = getCurlExamples();
   foreach (\$examples as \$name => \$command) {
       echo \"\$name:\\n\$command\\n\\n\";
   }

LARAVEL TINKER USAGE:
----------------------
php artisan tinker
require_once 'test_grievance_pagination.php';
createSampleGrievances();
testGrievancePagination();

POSTMAN/INSOMNIA TESTING:
------------------------
Import the following endpoints:
- GET /api/grievance/paginated
- GET /api/grievance/paginated-all

SAMPLE REQUEST URLS:
-------------------
";

$examples = getCurlExamples();
foreach ($examples as $name => $command) {
    echo "$name:\n$command\n\n";
}

echo "
RESPONSE STRUCTURE EXAMPLE:
--------------------------
{
  \"status\": 200,
  \"message\": \"Grievances retrieved successfully\",
  \"data\": {
    \"grievances\": [...],
    \"pagination\": {
      \"current_page\": 1,
      \"last_page\": 3,
      \"per_page\": 15,
      \"total\": 42,
      \"has_more_pages\": true
    },
    \"search_criteria\": {
      \"ration_card_number\": \"RC123456\",
      \"status\": null
    },
    \"status_counts\": {
      \"OPEN\": 15,
      \"IN_PROGRESS\": 8,
      \"CLOSED\": 12
    }
  }
}
====================================================
";