<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}

$offerId = $_GET['id'] ?? 0;
$userId = $_SESSION['user_id'] ?? 0;
if (!$offerId || !$userId) die("Missing offer ID or user session");

// Handle insert
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO partners_offer_tests 
        (offer_id, test_link, qa_status, validation_notes, tested_by)
        VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $offerId,
        $_POST['test_link'],
        $_POST['qa_status'],
        $_POST['validation_notes'],
        $userId
    ]);
    echo "<p class='success'>✅ Test entry saved.</p>";
}

// Fetch tests
$stmt = $pdo->prepare("SELECT t.*, u.username FROM partners_offer_tests t 
                       JOIN users u ON t.tested_by = u.id 
                       WHERE t.offer_id = ? ORDER BY t.tested_at DESC");
$stmt->execute([$offerId]);
$tests = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer QA Tests'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>🧪 Add QA Test for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
    <label>Test Link:<br>
        <input name="test_link" placeholder="Test Link">
    </label><br>
    <label>Status:
        <select name="qa_status">
            <option value="pending">Pending</option>
            <option value="passed">Passed</option>
            <option value="failed">Failed</option>
            <option value="needs_review">Needs Review</option>
        </select>
    </label><br>
    <label>Validation Notes:<br>
        <textarea name="validation_notes" placeholder="Validation Notes"></textarea>
    </label><br>
    <button type="submit">Save Test</button>
</form>

<hr><h3>📋 QA Test History</h3>
<table><tr><th>Status</th><th>Link</th><th>Notes</th><th>By</th><th>Time</th></tr>
<?php
foreach ($tests as $t) {
    echo "<tr>
        <td>" . htmlspecialchars($t['qa_status']) . "</td>
        <td><a href='" . htmlspecialchars($t['test_link']) . "' target='_blank'>View</a></td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($t['validation_notes']) . "</textarea></td>
        <td>" . htmlspecialchars($t['username']) . "</td>
        <td>{$t['tested_at']}</td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>