<?php
// POST /api/projects/test_request_create.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();

$projectId = (int)post('project_id', 0);
$title     = trim(post('title', ''));

if (!$projectId) apiError('Project ID required.', 422);
if (!$title)     apiError('Title required.', 422);

$db->prepare("
    INSERT INTO project_test_requests (project_id, section_id, title, description, requested_by, status)
    VALUES (?, ?, ?, ?, ?, 'pending')
")->execute([
    $projectId,
    post('section_id') ?: null,
    $title,
    post('description'),
    $user['id']
]);

$reqId = (int)$db->lastInsertId();

$db->prepare("INSERT INTO project_activity (project_id, user_id, action, entity_type, entity_id, details) VALUES (?, ?, 'test_request_created', 'test_request', ?, ?)")
   ->execute([$projectId, $user['id'], $reqId, json_encode(['title' => $title])]);

apiSuccess(['id' => $reqId], 'Test request created.', 201);
