<?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;
if (!$offerId) die("Missing offer ID");

// Handle geo targeting insert
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['geo_mode'])) {
    $stmt = $pdo->prepare("INSERT INTO partners_offer_geo 
        (offer_id, geo_type, geo_value, allowed, notes, redirect_url, advertiser_visible)
        VALUES (?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE allowed = VALUES(allowed), notes = VALUES(notes), redirect_url = VALUES(redirect_url), advertiser_visible = VALUES(advertiser_visible)");
    $stmt->execute([
        $offerId,
        $_POST['geo_type'],
        $_POST['geo_value'],
        isset($_POST['allowed']) ? 1 : 0,
        $_POST['notes'],
        $_POST['redirect_url'],
        isset($_POST['advertiser_visible']) ? 1 : 0
    ]);
    echo "<p class='success'>✅ Targeting rule saved.</p>";
}

// Handle payout modifier insert
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['payout_mode'])) {
    $stmt = $pdo->prepare("INSERT INTO partners_offer_geo_payouts 
        (offer_id, geo_type, geo_value, payout_modifier, notes)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE payout_modifier = VALUES(payout_modifier), notes = VALUES(notes)");
    $stmt->execute([
        $offerId,
        $_POST['geo_type'],
        $_POST['geo_value'],
        $_POST['payout_modifier'],
        $_POST['notes']
    ]);
    echo "<p class='success'>✅ Payout modifier saved.</p>";
}

// Fetch targeting rules
$stmt = $pdo->prepare("SELECT * FROM partners_offer_geo WHERE offer_id = ? ORDER BY geo_type, geo_value");
$stmt->execute([$offerId]);
$rules = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch payout modifiers
$stmt = $pdo->prepare("SELECT * FROM partners_offer_geo_payouts WHERE offer_id = ? ORDER BY geo_type, geo_value");
$stmt->execute([$offerId]);
$payouts = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Geo Targeting'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>🌍 Targeting Settings for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
    <input type="hidden" name="geo_mode" value="1">
    <label>Geo Type:
        <select name="geo_type">
            <option value="country">Country</option>
            <option value="state">State</option>
            <option value="language">Language</option>
        </select>
    </label><br>
    <label>Geo Value:<br>
        <input name="geo_value" placeholder="e.g. US, CA, Punjab, en">
    </label><br>
    <label><input type="checkbox" name="allowed" checked> Allowed</label><br>
    <label>Redirect URL:<br>
        <input name="redirect_url" placeholder="Redirect URL for disallowed traffic">
    </label><br>
    <label><input type="checkbox" name="advertiser_visible" checked> Visible to Advertiser</label><br>
    <label>Notes:<br>
        <textarea name="notes" placeholder="Notes (optional)"></textarea>
    </label><br>
    <button type="submit">Save Targeting</button>
</form>

<hr><h2>💰 Geo-Based Payout Modifier</h2>
<form method="post">
    <input type="hidden" name="payout_mode" value="1">
    <label>Geo Type:
        <select name="geo_type">
            <option value="country">Country</option>
            <option value="state">State</option>
            <option value="language">Language</option>
        </select>
    </label><br>
    <label>Geo Value:<br>
        <input name="geo_value" placeholder="e.g. US, CA, Punjab, en">
    </label><br>
    <label>Payout Modifier:<br>
        <input name="payout_modifier" placeholder="Modifier (e.g. 1.25)">
    </label><br>
    <label>Notes:<br>
        <textarea name="notes" placeholder="Notes (optional)"></textarea>
    </label><br>
    <button type="submit">Save Modifier</button>
</form>

<hr><h3>📋 Existing Targeting Rules</h3>
<table><tr>
    <th>Type</th><th>Value</th><th>Allowed</th><th>Redirect</th><th>Visible</th><th>Notes</th>
</tr>
<?php
foreach ($rules as $r) {
    echo "<tr>
        <td>" . htmlspecialchars($r['geo_type']) . "</td>
        <td>" . htmlspecialchars($r['geo_value']) . "</td>
        <td>" . ($r['allowed'] ? '✅' : '❌') . "</td>
        <td>" . ($r['redirect_url'] ? htmlspecialchars($r['redirect_url']) : '-') . "</td>
        <td>" . ($r['advertiser_visible'] ? '👁️' : '🙈') . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($r['notes']) . "</textarea></td>
    </tr>";
}
?>
</table>

<hr><h3>📊 Geo-Based Payout Modifiers</h3>
<table><tr>
    <th>Type</th><th>Value</th><th>Modifier</th><th>Notes</th>
</tr>
<?php
foreach ($payouts as $p) {
    echo "<tr>
        <td>" . htmlspecialchars($p['geo_type']) . "</td>
        <td>" . htmlspecialchars($p['geo_value']) . "</td>
        <td>" . htmlspecialchars($p['payout_modifier']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($p['notes']) . "</textarea></td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>