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

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Conversion Lookup'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$conversionId = $_GET['id'] ?? null;

echo "<h2>🔎 Conversion Lookup</h2>
<form method='get'>
    <input name='id' placeholder='Conversion ID' value='" . htmlspecialchars($conversionId) . "' required>
    <button type='submit'>Search</button>
</form>";

if ($conversionId) {
    // Conversion details
    $stmt = $pdo->prepare("
        SELECT c.*, a.name AS affiliate_name, o.name AS offer_name 
        FROM conversions c 
        JOIN affiliates a ON c.affiliate_id = a.id 
        JOIN offers o ON c.offer_id = o.id 
        WHERE c.id = ?
    ");
    $stmt->execute([$conversionId]);
    $conv = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$conv) {
        echo "<p class='error'>❌ Conversion not found.</p>";
        return;
    }

    echo "<h3>🧾 Conversion Details</h3>
    <table><tr><td>Affiliate</td><td>" . htmlspecialchars($conv['affiliate_name']) . " (#" . htmlspecialchars($conv['affiliate_id']) . ")</td></tr>
    <tr><td>Offer</td><td>" . htmlspecialchars($conv['offer_name']) . " (#" . htmlspecialchars($conv['offer_id']) . ")</td></tr>
    <tr><td>Amount</td><td>$" . number_format($conv['payout_amount'], 2) . "</td></tr>
    <tr><td>Status</td><td>" . htmlspecialchars($conv['status']) . "</td></tr>
    <tr><td>IP</td><td>" . htmlspecialchars($conv['ip_address']) . "</td></tr>
    <tr><td>Geo</td><td>" . htmlspecialchars($conv['geo_source']) . "</td></tr>
    <tr><td>Device</td><td>" . htmlspecialchars($conv['device_type']) . "</td></tr>
    <tr><td>Time</td><td>{$conv['created_at']}</td></tr>
    </table>";

    // Postback attempts
    $postStmt = $pdo->prepare("
        SELECT * FROM partners_postback_logs 
        WHERE postback_id = ? ORDER BY fire_time DESC
    ");
    $postStmt->execute([$conversionId]);
    $posts = $postStmt->fetchAll(PDO::FETCH_ASSOC);

    echo "<h3>📥 Postback Attempts</h3>
    <table><tr>
        <th>Time</th><th>Status</th><th>Code</th><th>Response</th><th>Attempt</th>
    </tr>";
    foreach ($posts as $p) {
        echo "<tr>
            <td>{$p['fire_time']}</td>
            <td>" . htmlspecialchars($p['delivery_status']) . "</td>
            <td>" . htmlspecialchars($p['response_code']) . "</td>
            <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($p['response_body']) . "</textarea></td>
            <td>" . htmlspecialchars($p['attempt']) . "</td>
        </tr>";
    }
    echo "</table>";
}
?>
</div>
</body>
</html>