<?php
require 'vendor/autoload.php';
$app = require_once 'bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();

// Login first
$loginResponse = app('router')->dispatch(
    \Illuminate\Http\Request::create('/api/auth/login', 'POST', [
        'email' => 'admin@gcm.co.ke',
        'password' => 'password',
    ])
);
$loginData = json_decode($loginResponse->getContent(), true);
$token = $loginData['access_token'] ?? null;

if (!$token) {
    echo "Login failed: " . $loginResponse->getContent() . "\n";
    exit(1);
}
echo "Token: " . substr($token, 0, 20) . "...\n";

// Get a project compliance item
$headers = ['HTTP_AUTHORIZATION' => 'Bearer ' . $token];

// First get projects
$projectsResp = app('router')->dispatch(
    \Illuminate\Http\Request::create('/api/projects', 'GET', [], [], [], $headers)
);
$projects = json_decode($projectsResp->getContent(), true);
$projectId = $projects['data'][0]['id'] ?? null;
echo "Project ID: $projectId\n";

if (!$projectId) {
    echo "No projects found\n";
    exit(1);
}

// Get compliance for project
$compResp = app('router')->dispatch(
    \Illuminate\Http\Request::create("/api/projects/{$projectId}/compliance", 'GET', [], [], [], $headers)
);
$compData = json_decode($compResp->getContent(), true);
echo "Compliance status: " . $compResp->getStatusCode() . "\n";
echo "Items count: " . count($compData['data'] ?? []) . "\n";

if (empty($compData['data'])) {
    echo "No compliance items, trying bulk assign...\n";
    $bulkResp = app('router')->dispatch(
        \Illuminate\Http\Request::create("/api/projects/{$projectId}/compliance/bulk-assign", 'POST', [], [], [], $headers)
    );
    echo "Bulk assign: " . $bulkResp->getContent() . "\n";
    
    // Re-fetch
    $compResp = app('router')->dispatch(
        \Illuminate\Http\Request::create("/api/projects/{$projectId}/compliance", 'GET', [], [], [], $headers)
    );
    $compData = json_decode($compResp->getContent(), true);
    echo "Items count now: " . count($compData['data'] ?? []) . "\n";
}

$firstItem = $compData['data'][0] ?? null;
if (!$firstItem) {
    echo "No compliance items available\n";
    exit(1);
}

$pcrId = $firstItem['id'];
echo "PCR ID: $pcrId, Status: " . ($firstItem['status'] ?? 'null') . "\n";

// TEST 1: Update the item
echo "\n--- TEST: Update compliance item ---\n";
$updateReq = \Illuminate\Http\Request::create("/api/project-compliance/{$pcrId}", 'PUT', [
    'status' => 'done',
    'notes' => 'Test update',
], [], [], $headers);
$updateReq->headers->set('Content-Type', 'application/json');

$updateResp = app('router')->dispatch($updateReq);
echo "Update status: " . $updateResp->getStatusCode() . "\n";
echo "Update response: " . substr($updateResp->getContent(), 0, 500) . "\n";

echo "\nDone.\n";
