<?php
// api/get_active_contract_for_client.php?clientId=47
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../../config.php';

$clientId = isset($_GET['clientId']) ? (int)$_GET['clientId'] : 0;
if ($clientId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid clientId']);
    exit;
}

try {
    // Pick the latest Active contract for this client.
    // Adjust WHERE/ORDER BY if your schema uses different statuses.
    $sql = "
        SELECT Id
        FROM ClientContracts
        WHERE ClientId = :clientId
          AND Status = 'Active'
        ORDER BY Id DESC
        LIMIT 1
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':clientId' => $clientId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode([
            'success'    => false,
            'message'    => 'No active contract found for this client',
            'contractId' => null
        ]);
        exit;
    }

    echo json_encode([
        'success'    => true,
        'message'    => 'OK',
        'contractId' => (int)$row['Id']
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load active contract',
        'details' => $e->getMessage()
    ]);
}
