<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
auth_require_login();
$pdo = crm_pdo();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); echo json_encode(['ok'=>false,'error'=>'Method not allowed']); exit;
}

gp_require_csrf();

$requestId = (int)($_POST['request_id'] ?? 0);
$trackingNumber = trim((string)($_POST['tracking_number'] ?? ''));
$userId = (int)(auth_user()['id'] ?? 0);

if ($requestId <= 0) {
    echo json_encode(['ok'=>false,'error'=>'Invalid request ID']); exit;
}
if ($trackingNumber === '') {
    echo json_encode(['ok'=>false,'error'=>'Tracking number cannot be empty']); exit;
}

// Only admin/manager can fulfill
$role = auth_user()['role'] ?? '';
if (!in_array($role, ['ADMIN', 'MANAGER'], true)) {
    echo json_encode(['ok'=>false,'error'=>'Permission denied. Only Admins or Managers can fulfill missing part requests.']); exit;
}

// Update request
$stmt = $pdo->prepare("
    UPDATE project_missing_parts 
    SET status = 'sent', tracking_number = ?, manager_user_id = ? 
    WHERE id = ? AND status = 'pending'
");
$ok = $stmt->execute([$trackingNumber, $userId, $requestId]);

if ($stmt->rowCount() > 0) {
    echo json_encode(['ok' => true]);
} else {
    echo json_encode(['ok' => false, 'error' => 'Request not found or already fulfilled']);
}
