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

require_once __DIR__ . '/../config/config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

$success_msg = '';
$error_msg = '';

// ---------------------------------------------------------
// AD CAMPAIGN CRUD OPERATIONS
// ---------------------------------------------------------

// 1. CREATE: Handle New Ad Placement
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_campaign'])) {
    $campaign_name = trim($_POST['campaign_name'] ?? '');
    $slot          = trim($_POST['slot'] ?? 'in_content');
    $target_url    = trim($_POST['target_url'] ?? '');
    $banner_code   = trim($_POST['banner_code'] ?? '');
    $status        = trim($_POST['status'] ?? 'ACTIVE');

    if (!empty($campaign_name) && !empty($banner_code)) {
        $stmt = $pdo->prepare("INSERT INTO campaigns (campaign_name, slot, target_url, banner_code, status) VALUES (?, ?, ?, ?, ?)");
        if ($stmt->execute([$campaign_name, $slot, $target_url, $banner_code, $status])) {
            $success_msg = "Ad campaign successfully published!";
        } else {
            $error_msg = "Failed to save the ad campaign.";
        }
    } else {
        $error_msg = "Campaign Name and Banner Code are required.";
    }
}

// 2. UPDATE: Handle Full Record Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_campaign'])) {
    $id            = intval($_POST['edit_id'] ?? 0);
    $campaign_name = trim($_POST['campaign_name'] ?? '');
    $slot          = trim($_POST['slot'] ?? 'in_content');
    $target_url    = trim($_POST['target_url'] ?? '');
    $banner_code   = trim($_POST['banner_code'] ?? '');
    $status        = trim($_POST['status'] ?? 'ACTIVE');

    if ($id > 0 && !empty($campaign_name) && !empty($banner_code)) {
        $stmt = $pdo->prepare("UPDATE campaigns SET campaign_name=?, slot=?, target_url=?, banner_code=?, status=? WHERE id=?");
        if ($stmt->execute([$campaign_name, $slot, $target_url, $banner_code, $status, $id])) {
            $success_msg = "Ad campaign updated successfully!";
        } else {
            $error_msg = "Failed to update ad campaign.";
        }
    }
}

// 3. UPDATE: Quick Status Toggle
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quick_status_update'])) {
    $campaign_id = intval($_POST['campaign_id'] ?? 0);
    $new_status  = $_POST['new_status'] ?? 'ACTIVE';
    
    if ($campaign_id > 0) {
        $update_stmt = $pdo->prepare("UPDATE campaigns SET status = ? WHERE id = ?");
        $update_stmt->execute([$new_status, $campaign_id]);
        $success_msg = "Campaign status updated!";
    }
}

// 4. DELETE: Remove Campaign
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_campaign'])) {
    $campaign_id = intval($_POST['delete_id'] ?? 0);
    if ($campaign_id > 0) {
        $delete_stmt = $pdo->prepare("DELETE FROM campaigns WHERE id = ?");
        if ($delete_stmt->execute([$campaign_id])) {
            $success_msg = "Ad campaign permanently deleted.";
        }
    }
}

// ---------------------------------------------------------
// DATA FETCHING & EDIT MODE LOGIC
// ---------------------------------------------------------
$edit_mode = false;
$edit_data = [];
if (isset($_GET['edit'])) {
    $edit_mode = true;
    $stmt = $pdo->prepare("SELECT * FROM campaigns WHERE id = ?");
    $stmt->execute([intval($_GET['edit'])]);
    $edit_data = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Fetch all campaigns for the table
$stmt = $pdo->query("SELECT * FROM campaigns ORDER BY id DESC");
$campaigns = $stmt->fetchAll(PDO::FETCH_ASSOC);

$active_slots = 0;
foreach ($campaigns as $c) {
    if ($c['status'] === 'ACTIVE') $active_slots++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Ad Campaign Manager</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') document.documentElement.classList.add('dark');
        else document.documentElement.classList.remove('dark');
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-6 md:p-10 overflow-x-hidden flex flex-col gap-6">
        
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
                <h2 class="text-3xl font-bold text-slate-900 dark:text-white tracking-wide">Ad Campaign Manager</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-1">Deploy and control 3rd-party advertising banners across your platform</p>
            </div>
        </div>

        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-600 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-500 border p-4 rounded-xl text-sm font-semibold shadow-sm"><?php echo htmlspecialchars($success_msg); ?></div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-600 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-500 border p-4 rounded-xl text-sm font-semibold shadow-sm"><?php echo htmlspecialchars($error_msg); ?></div>
        <?php endif; ?>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 p-5 rounded-2xl flex flex-col justify-between shadow-sm transition-colors duration-300">
                <span class="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider font-semibold">Live Ad Campaigns</span>
                <span class="text-2xl font-extrabold text-blue-600 dark:text-blue-500 mt-1"><?php echo $active_slots; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 p-5 rounded-2xl flex flex-col justify-between shadow-sm transition-colors duration-300 opacity-60">
                <span class="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider font-semibold">Total Banner Clicks</span>
                <span class="text-2xl font-extrabold text-slate-900 dark:text-white mt-1">N/A</span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 p-5 rounded-2xl flex flex-col justify-between shadow-sm transition-colors duration-300 opacity-60">
                <span class="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider font-semibold">Est. Ad Revenue</span>
                <span class="text-2xl font-extrabold text-emerald-600 dark:text-emerald-500 mt-1">$0.00</span>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-6 h-fit shadow-sm transition-colors duration-300">
                
                <div class="flex items-center justify-between border-b border-slate-200 dark:border-slate-800 pb-3 mb-6">
                    <h3 class="font-bold text-lg text-slate-900 dark:text-white">
                        <?php echo $edit_mode ? '✏️ Edit Ad Campaign' : '📢 New Ad Placement'; ?>
                    </h3>
                    <?php if($edit_mode): ?>
                        <a href="monetization.php" class="text-[10px] bg-slate-200 text-slate-600 dark:bg-slate-800 dark:text-gray-400 px-2 py-1 rounded font-bold uppercase tracking-wider hover:bg-slate-300 dark:hover:bg-slate-700 transition">Cancel</a>
                    <?php endif; ?>
                </div>

                <form action="monetization.php" method="POST" class="space-y-4">
                    <?php if($edit_mode): ?>
                        <input type="hidden" name="edit_id" value="<?php echo $edit_data['id']; ?>">
                    <?php endif; ?>

                    <div>
                        <label class="block text-xs text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-semibold">Campaign Name</label>
                        <input type="text" name="campaign_name" value="<?php echo $edit_mode ? htmlspecialchars($edit_data['campaign_name']) : ''; ?>" required placeholder="e.g. 1Win Main Banner" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-emerald-500 text-sm transition-colors">
                    </div>
                    
                    <div>
                        <label class="block text-xs text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-semibold">Placement Slot</label>
                        <select name="slot" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-emerald-500 text-sm transition-colors">
                            <option value="header" <?php echo ($edit_mode && $edit_data['slot'] == 'header') ? 'selected' : ''; ?>>Header Top Banner</option>
                            <option value="sidebar" <?php echo ($edit_mode && $edit_data['slot'] == 'sidebar') ? 'selected' : ''; ?>>Sidebar Widget</option>
                            <option value="in_content" <?php echo ($edit_mode && $edit_data['slot'] == 'in_content') ? 'selected' : ''; ?>>In-Content Feed</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-semibold">Target Click URL</label>
                        <input type="url" name="target_url" value="<?php echo $edit_mode ? htmlspecialchars($edit_data['target_url'] ?? '') : ''; ?>" placeholder="https://..." class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-emerald-500 text-sm transition-colors">
                    </div>

                    <div>
                        <label class="block text-xs text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-semibold">Image URL or HTML Ad Code</label>
                        <textarea name="banner_code" rows="5" required placeholder="Paste the HTML script or raw Image URL here..." class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-emerald-500 text-sm transition-colors font-mono text-[10px] leading-relaxed"><?php echo $edit_mode ? htmlspecialchars($edit_data['banner_code']) : ''; ?></textarea>
                    </div>

                    <div>
                        <label class="block text-xs text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-semibold">Status</label>
                        <select name="status" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-emerald-500 text-sm transition-colors">
                            <option value="ACTIVE" <?php echo ($edit_mode && $edit_data['status'] == 'ACTIVE') ? 'selected' : ''; ?>>🟢 ACTIVE (Displaying)</option>
                            <option value="PAUSED" <?php echo ($edit_mode && $edit_data['status'] == 'PAUSED') ? 'selected' : ''; ?>>⏸️ PAUSED (Hidden)</option>
                        </select>
                    </div>

                    <?php if($edit_mode): ?>
                        <button type="submit" name="update_campaign" class="w-full bg-emerald-500 hover:bg-emerald-600 text-white font-bold py-3.5 rounded-xl transition mt-4 shadow-lg shadow-emerald-500/20 text-sm tracking-wider uppercase">Update Ad Placement</button>
                    <?php else: ?>
                        <button type="submit" name="add_campaign" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition mt-4 shadow-lg shadow-blue-600/20 text-sm tracking-wider uppercase">Deploy New Ad</button>
                    <?php endif; ?>
                </form>
            </div>

            <div class="lg:col-span-2 space-y-6">
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-6 shadow-sm transition-colors duration-300">
                    <h3 class="font-bold text-lg mb-6 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">Active Ad Inventory</h3>
                    
                    <div class="overflow-x-auto">
                        <table class="w-full text-left text-sm border-collapse">
                            <thead>
                                <tr class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800 text-xs tracking-wider">
                                    <th class="py-3 px-2 font-semibold">Ad Campaign</th>
                                    <th class="py-3 px-2 font-semibold text-center">Location Slot</th>
                                    <th class="py-3 px-2 font-semibold text-center">Status</th>
                                    <th class="py-3 px-2 font-semibold text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300 text-xs">
                                
                                <?php foreach($campaigns as $camp): ?>
                                <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition group">
                                    <td class="py-3 px-2 whitespace-nowrap">
                                        <div class="font-bold text-slate-900 dark:text-white mb-0.5 text-sm"><?php echo htmlspecialchars($camp['campaign_name']); ?></div>
                                        <div class="text-[10px] text-slate-500 dark:text-gray-400 line-clamp-1 max-w-[200px]"><?php echo htmlspecialchars($camp['target_url'] ?: 'No click URL'); ?></div>
                                    </td>
                                    <td class="py-3 px-2 text-center whitespace-nowrap">
                                        <span class="bg-slate-100 text-slate-600 border border-slate-200 dark:bg-slate-800 dark:border-slate-700 dark:text-gray-300 px-2 py-1 rounded text-[10px] font-bold uppercase"><?php echo htmlspecialchars(str_replace('_', ' ', $camp['slot'])); ?></span>
                                    </td>
                                    
                                    <td class="py-3 px-2 text-center whitespace-nowrap">
                                        <form action="monetization.php" method="POST" class="inline-block">
                                            <input type="hidden" name="campaign_id" value="<?php echo $camp['id']; ?>">
                                            <input type="hidden" name="quick_status_update" value="1">
                                            <select name="new_status" onchange="this.form.submit()" class="bg-slate-50 border-slate-200 text-slate-900 dark:bg-slate-950 border dark:border-slate-800 text-[10px] dark:text-white rounded p-1 focus:outline-none font-bold tracking-wider cursor-pointer <?php echo $camp['status'] === 'ACTIVE' ? 'text-emerald-600 dark:text-emerald-500' : 'text-amber-600 dark:text-amber-500'; ?>">
                                                <option value="ACTIVE" <?php if($camp['status']=='ACTIVE') echo 'selected'; ?>>🟢 ACTIVE</option>
                                                <option value="PAUSED" <?php if($camp['status']=='PAUSED') echo 'selected'; ?>>⏸️ PAUSED</option>
                                            </select>
                                        </form>
                                    </td>

                                    <td class="py-3 px-2 text-right whitespace-nowrap">
                                        <div class="flex items-center justify-end space-x-2">
                                            <a href="monetization.php?edit=<?php echo $camp['id']; ?>" class="bg-blue-50 text-blue-600 border border-blue-200 hover:bg-blue-100 dark:bg-blue-500/10 dark:text-blue-500 dark:border-blue-500/30 dark:hover:bg-blue-500/20 px-2 py-1.5 rounded text-[10px] font-bold uppercase transition">Edit</a>
                                            <form action="monetization.php" method="POST" onsubmit="return confirm('Delete this ad completely?');" class="inline">
                                                <input type="hidden" name="delete_id" value="<?php echo $camp['id']; ?>">
                                                <button type="submit" name="delete_campaign" class="bg-rose-50 text-rose-600 border border-rose-200 hover:bg-rose-100 dark:bg-rose-500/10 dark:text-rose-500 dark:border-rose-500/30 dark:hover:bg-rose-500/20 px-2 py-1.5 rounded text-[10px] font-bold uppercase transition">Del</button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                
                                <?php if(empty($campaigns)): ?>
                                <tr><td colspan="4" class="py-8 text-center text-slate-400 dark:text-gray-500">No active advertisements. Add your first campaign to the left!</td></tr>
                                <?php endif; ?>

                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </main>
</body>
</html>