<?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");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Caps'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$offerId = $_GET['id'] ?? 0;
if (!$offerId) die("Missing offer ID");

// Handle insert/update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO partners_offer_caps 
        (offer_id, affiliate_id, cap_type, cap_limit, auto_pause, notes, rollover_enabled, reset_interval, overflow_redirect, advertiser_visible)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $offerId,
        $_POST['affiliate_id'] ?? 0,
        $_POST['cap_type'],
        $_POST['cap_limit'],
        isset($_POST['auto_pause']) ? 1 : 0,
        $_POST['notes'],
        isset($_POST['rollover_enabled']) ? 1 : 0,
        $_POST['reset_interval'] ?: null,
        $_POST['overflow_redirect'] ?: null,
        isset($_POST['advertiser_visible']) ? 1 : 0
    ]);
    echo "<p class='success'>✅ Cap saved.</p>";
}

// Fetch caps
$stmt = $pdo->prepare("SELECT c.*, u.username FROM partners_offer_caps c 
                       LEFT JOIN users u ON c.affiliate_id = u.id 
                       WHERE c.offer_id = ? ORDER BY c.cap_type, c.affiliate_id");
$stmt->execute([$offerId]);
$caps = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Cap form
echo "<h2>📊 Set Cap for Offer #" . htmlspecialchars($offerId) . "</h2>
<form method='post'>
    <label>Affiliate ID (0 for global):<br><input name='affiliate_id' value='0'></label><br>
    <label>Cap Type:
        <select name='cap_type'>
            <option value='hourly'>Hourly</option>
            <option value='daily'>Daily</option>
            <option value='weekly'>Weekly</option>
            <option value='monthly'>Monthly</option>
            <option value='total'>Total</option>
        </select>
    </label><br>
    <label>Cap Limit:<br><input name='cap_limit' placeholder='Cap Limit'></label><br>
    <label><input type='checkbox' name='auto_pause'> Auto-pause when cap is hit</label><br>
    <label><input type='checkbox' name='rollover_enabled'> Enable rollover</label><br>
    <label>Reset Interval:
        <select name='reset_interval'>
            <option value=''>-- Reset Interval --</option>
            <option value='hourly'>Hourly</option>
            <option value='daily'>Daily</option>
            <option value='weekly'>Weekly</option>
            <option value='monthly'>Monthly</option>
        </select>
    </label><br>
    <label>Overflow Redirect URL:<br><input name='overflow_redirect'></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 Cap</button>
</form>";

echo "<hr><h2>📋 Existing Caps</h2>
<table><tr>
    <th>Type</th><th>Limit</th><th>Current</th><th>Affiliate</th><th>Auto-Pause</th>
    <th>Rollover</th><th>Reset</th><th>Overflow</th><th>Visible</th><th>Notes</th>
</tr>";
foreach ($caps as $c) {
    $aff = $c['affiliate_id'] == 0 ? 'Global' : htmlspecialchars($c['username']) . " (#" . htmlspecialchars($c['affiliate_id']) . ")";
    echo "<tr>
        <td>" . htmlspecialchars($c['cap_type']) . "</td>
        <td>" . htmlspecialchars($c['cap_limit']) . "</td>
        <td>" . htmlspecialchars($c['current_count']) . "</td>
        <td>$aff</td>
        <td>" . ($c['auto_pause'] ? '✅' : '❌') . "</td>
        <td>" . ($c['rollover_enabled'] ? '🔁' : '-') . "</td>
        <td>" . ($c['reset_interval'] ?: '-') . "</td>
        <td>" . ($c['overflow_redirect'] ?: '-') . "</td>
        <td>" . ($c['advertiser_visible'] ? '👁️' : '🙈') . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($c['notes']) . "</textarea></td>
    </tr>";
}
echo "</table>";
?>
</div>
</body>
</html>