<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


require_once '../config.php';
$conn = require_once '../db.php';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $url = trim($_POST['url'] ?? '');
        $duration = intval($_POST['duration_sec'] ?? 10);
        $amount = floatval($_POST['amount'] ?? 0.008);

        if ($url) {
            $stmt = $conn->prepare("INSERT INTO website_ads (url, duration_sec, amount, total_views, status, created_at) VALUES (?, ?, ?, 0, 1, NOW())");
            if (!$stmt) {
                die("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("sid", $url, $duration, $amount);
            $stmt->execute();
            $stmt->close();

            $_SESSION['message'] = "✅ New Ad Added Successfully!";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
    } elseif ($action === 'edit') {
        $id = intval($_POST['id'] ?? 0);
        $url = trim($_POST['url'] ?? '');
        $duration = intval($_POST['duration_sec'] ?? 10);
        $amount = floatval($_POST['amount'] ?? 0.008);

        if ($id && $url) {
            $stmt = $conn->prepare("UPDATE website_ads SET url=?, duration_sec=?, amount=? WHERE id=?");
            if (!$stmt) {
                die("Prepare failed: " . $conn->error);
            }
            // bind_param types: s = string, i = int, d = double, i = int (id)
            $stmt->bind_param("sidi", $url, $duration, $amount, $id);
            $stmt->execute();
            $stmt->close();

            $_SESSION['message'] = "✅ Ad Updated Successfully!";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
    } elseif ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        if ($id) {
            $stmt = $conn->prepare("DELETE FROM website_ads WHERE id=?");
            if (!$stmt) {
                die("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();

            $_SESSION['message'] = "❌ Ad Deleted Successfully!";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
    }
}

// Fetch for edit
$edit_ad = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM website_ads WHERE id=?");
    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $edit_ad = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

// Fetch all ads
$ads = $conn->query("SELECT * FROM website_ads ORDER BY created_at DESC");
if (!$ads) {
    die("Query failed: " . $conn->error);
}

require_once 'includes/header.php';
?>



<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Website Ads Manager</title>
<style>
    body { background: #f4f7fc; font-family: 'Segoe UI', sans-serif; padding: 20px; margin:0; }
    h1 { text-align: center; color: #007bff; font-weight: 800; margin-bottom: 30px; }
    .form, .card {
        background: #fff; border: 2px solid #007bff40;
        padding: 20px; border-radius: 10px;
        box-shadow: 0 5px 15px rgba(0,123,255,0.1);
        margin-bottom: 25px;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    .form:hover, .card:hover {
        transform: scale(1.02);
        box-shadow: 0 8px 20px rgba(0,123,255,0.25);
    }
    input[type=text], input[type=number] {
        width: 100%; padding: 12px; margin: 10px 0 20px;
        border: 2px solid #007bff40; border-radius: 8px;
        transition: all 0.3s;
        font-size: 16px;
    }
    input[type=text]:focus, input[type=number]:focus {
        border-color: #0056b3;
        outline: none;
        box-shadow: 0 0 8px #0056b3;
    }
    input[type=submit], button {
        background: #007bff; color: #fff; padding: 12px 20px; border: none;
        border-radius: 8px; cursor: pointer; font-weight: bold;
        font-size: 16px;
        user-select: none;
        transition: background-color 0.25s ease;
    }
    input[type=submit]:hover, button:hover {
        background: #0056b3;
    }
    .card {
        border-left: 8px solid #007bff;
        position: relative;
    }
    .card h3 {
        color: #333;
        margin: 0 0 10px 0;
        word-break: break-word;
    }
    .card p {
        margin: 6px 0;
        font-size: 15px;
        color: #555;
    }
    .actions {
        margin-top: 15px;
        position: absolute;
        right: 20px;
        bottom: 20px;
    }
    .actions form {
        display: inline-block;
        margin-left: 8px;
    }
    .actions button, .actions a button {
        padding: 8px 15px;
        font-size: 14px;
        margin-left: 5px;
    }
    .btn-edit {
        background-color: #ffc107;
        color: #212529;
        border: 1.5px solid #e0a800;
    }
    .btn-edit:hover {
        background-color: #e0a800;
    }
    .btn-delete {
        background-color: #dc3545;
        border: 1.5px solid #bd2130;
    }
    .btn-delete:hover {
        background-color: #bd2130;
    }
    .message {
        background: #d1e7dd; color: #0f5132;
        padding: 12px; border: 1px solid #badbcc;
        border-radius: 8px; margin-bottom: 20px;
        text-align: center; font-weight: bold;
        max-width: 600px;
        margin-left: auto;
        margin-right: auto;
        user-select: none;
    }
    @media(max-width: 600px) {
        .actions {
            position: static;
            margin-top: 12px;
            text-align: right;
        }
        .actions form {
            margin-left: 5px;
        }
    }
</style>
</head>
<body>

<h1>🌐 Website Ads Manager</h1>

<?php if (!empty($_SESSION['message'])): ?>
    <div class="message"><?php echo htmlspecialchars($_SESSION['message']); unset($_SESSION['message']); ?></div>
<?php endif; ?>

<div class="form" role="form">
    <h3><?= $edit_ad ? "✏️ Edit Ad" : "➕ Add New Ad" ?></h3>
    <form method="POST" novalidate>
        <input type="hidden" name="action" value="<?= $edit_ad ? 'edit' : 'add' ?>">
        <?php if ($edit_ad): ?>
            <input type="hidden" name="id" value="<?= (int)$edit_ad['id'] ?>">
        <?php endif; ?>

        <label for="url">Website URL:</label>
        <input type="text" id="url" name="url" required placeholder="https://example.com" value="<?= htmlspecialchars($edit_ad['url'] ?? '') ?>">

        <label for="duration_sec">Duration (Seconds):</label>
        <input type="number" id="duration_sec" name="duration_sec" required min="5" max="3600" value="<?= (int)($edit_ad['duration_sec'] ?? 10) ?>">

        <label for="amount">Reward per Visit (৳):</label>
        <input type="text" id="amount" name="amount" required pattern="^\d+(\.\d{1,4})?$" title="Enter a valid number like 0.008" value="<?= htmlspecialchars($edit_ad['amount'] ?? '0.008') ?>">

        <input type="submit" value="<?= $edit_ad ? 'Update Ad' : 'Add Ad' ?>">
    </form>
</div>

<?php while ($ad = $ads->fetch_assoc()): ?>
    <div class="card">
        <h3>🔗 <?= htmlspecialchars($ad['url']) ?></h3>
        <p>⏱️ Duration: <strong><?= (int)$ad['duration_sec'] ?> seconds</strong></p>
        <p>💰 Reward: <strong>৳<?= number_format($ad['amount'], 4) ?></strong></p>
        <p>👁️ Views: <strong><?= (int)$ad['total_views'] ?></strong></p>
        <div class="actions">
            <a href="?edit=<?= (int)$ad['id'] ?>"><button type="button" class="btn-edit">✏️ Edit</button></a>
            <form method="POST" onsubmit="return confirm('Are you sure to delete this ad?');" style="display:inline;">
                <input type="hidden" name="action" value="delete" />
                <input type="hidden" name="id" value="<?= (int)$ad['id'] ?>" />
                <button type="submit" class="btn-delete">🗑️ Delete</button>
            </form>
        </div>
    </div>
<?php endwhile; ?>

<?php
require_once 'includes/footer.php';  // ফুটার ফাইল include করুন
?>
</body>
</html>