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

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

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

if (!$testRequestId) apiError('Test request ID required.', 422);
if (!$projectId)     apiError('Project ID required.', 422);
if (!$title)         apiError('Title required.', 422);
if (!$description)   apiError('Description required.', 422);

$db->prepare("
    INSERT INTO project_bugs (test_request_id, project_id, todo_id, title, description, severity, status, reported_by, assigned_to)
    VALUES (?, ?, ?, ?, ?, ?, 'open', ?, ?)
")->execute([
    $testRequestId, $projectId,
    post('todo_id') ?: null,
    $title, $description,
    post('severity', 'minor'),
    $user['id'],
    post('assigned_to') ?: null
]);

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

// Update test request status
$db->prepare("UPDATE project_test_requests SET status = 'bugs_found', updated_at = NOW() WHERE id = ?")
   ->execute([$testRequestId]);

$db->prepare("INSERT INTO project_activity (project_id, user_id, action, entity_type, entity_id, details) VALUES (?, ?, 'bug_reported', 'bug', ?, ?)")
   ->execute([$projectId, $user['id'], $bugId, json_encode(['title' => $title, 'severity' => post('severity', 'minor')])]);

apiSuccess(['id' => $bugId], 'Bug reported.', 201);
