<?php
require_once '../includes/require_admin.php';
require_once '../includes/header.php';
require_once '../includes/marketing_functions.php';

// Handle form submissions
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_discount'])) {
        $product_id = !empty($_POST['product_id']) ? (int)$_POST['product_id'] : null;
        $discount_percentage = (float)$_POST['discount_percentage'];
        $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        try {
            $stmt = $pdo->prepare("INSERT INTO discounts (product_id, discount_percentage, start_date, end_date, is_active) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$product_id, $discount_percentage, $start_date, $end_date, $is_active]);
            $message = '<div class="message success">Discount added successfully!</div>';
        } catch (Exception $e) {
            $message = '<div class="message error">Error adding discount: ' . $e->getMessage() . '</div>';
        }
    } elseif (isset($_POST['add_advertisement'])) {
        $title = sanitizeInput($_POST['title']);
        $description = sanitizeInput($_POST['description']);
        $image_url = !empty($_POST['image_url']) ? sanitizeInput($_POST['image_url']) : null;
        $link_url = !empty($_POST['link_url']) ? sanitizeInput($_POST['link_url']) : null;
        $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
        $position = sanitizeInput($_POST['position']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        try {
            $stmt = $pdo->prepare("INSERT INTO advertisements (title, description, image_url, link_url, start_date, end_date, position, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$title, $description, $image_url, $link_url, $start_date, $end_date, $position, $is_active]);
            $message = '<div class="message success">Advertisement added successfully!</div>';
        } catch (Exception $e) {
            $message = '<div class="message error">Error adding advertisement: ' . $e->getMessage() . '</div>';
        }
    }
}

// Get all products for discount form
$products = getAllProducts($pdo);

// Get existing discounts and advertisements
$discounts = getActiveDiscounts($pdo);
$advertisements = getActiveAdvertisements($pdo, 'homepage');
?>

<div class="container">
    <div class="admin-header">
        <h2>Marketing Management</h2>
    </div>
    
    <div class="admin-nav">
        <ul>
            <li><a href="<?php echo SITE_URL; ?>/admin/index.php">Dashboard</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/products.php">Products</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/manage_users.php">Users</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/orders.php">Orders</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/marketing.php" class="active">Marketing</a></li>
        </ul>
    </div>
    
    <?php echo $message; ?>
    
    <!-- Add Discount Form -->
    <div class="checkout-form">
        <h3>Add New Discount</h3>
        <form method="POST" action="">
            <div class="form-group">
                <label for="product_id">Product (Optional - leave blank for category discount)</label>
                <select id="product_id" name="product_id">
                    <option value="">Select a product (optional)</option>
                    <?php foreach ($products as $product): ?>
                        <option value="<?php echo $product['id']; ?>"><?php echo htmlspecialchars($product['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label for="discount_percentage">Discount Percentage (%)</label>
                <input type="number" id="discount_percentage" name="discount_percentage" step="0.01" min="0" max="100" required>
            </div>
            
            <div class="form-group">
                <label for="start_date">Start Date (Optional)</label>
                <input type="datetime-local" id="start_date" name="start_date">
            </div>
            
            <div class="form-group">
                <label for="end_date">End Date (Optional)</label>
                <input type="datetime-local" id="end_date" name="end_date">
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" name="is_active" value="1" checked> Active
                </label>
            </div>
            
            <button type="submit" name="add_discount" class="btn btn-primary">Add Discount</button>
        </form>
    </div>
    
    <!-- Add Advertisement Form -->
    <div class="checkout-form" style="margin-top: 30px;">
        <h3>Add New Advertisement</h3>
        <form method="POST" action="">
            <div class="form-group">
                <label for="title">Title</label>
                <input type="text" id="title" name="title" required>
            </div>
            
            <div class="form-group">
                <label for="description">Description</label>
                <textarea id="description" name="description" rows="3"></textarea>
            </div>
            
            <div class="form-group">
                <label for="image_url">Image URL (Optional)</label>
                <input type="text" id="image_url" name="image_url">
            </div>
            
            <div class="form-group">
                <label for="link_url">Link URL (Optional)</label>
                <input type="text" id="link_url" name="link_url">
            </div>
            
            <div class="form-group">
                <label for="position">Position</label>
                <select id="position" name="position">
                    <option value="homepage">Homepage</option>
                    <option value="product_page">Product Page</option>
                    <option value="category_page">Category Page</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="start_date_ad">Start Date (Optional)</label>
                <input type="datetime-local" id="start_date_ad" name="start_date">
            </div>
            
            <div class="form-group">
                <label for="end_date_ad">End Date (Optional)</label>
                <input type="datetime-local" id="end_date_ad" name="end_date">
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" name="is_active" value="1" checked> Active
                </label>
            </div>
            
            <button type="submit" name="add_advertisement" class="btn btn-primary">Add Advertisement</button>
        </form>
    </div>
    
    <!-- Current Discounts -->
    <div class="section-title">
        <h2>Current Discounts</h2>
    </div>
    
    <?php if (empty($discounts)): ?>
        <p>No active discounts found.</p>
    <?php else: ?>
        <div class="cart-table">
            <table>
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Discount %</th>
                        <th>Original Price</th>
                        <th>Discounted Price</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($discounts as $discount): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($discount['product_name'] ?? 'All Products'); ?></td>
                            <td><?php echo number_format($discount['discount_percentage'], 2); ?>%</td>
                            <td>$<?php echo number_format($discount['original_price'] ?? 0, 2); ?></td>
                            <td>$<?php echo number_format(getDiscountedPrice($discount['original_price'] ?? 0, $discount['discount_percentage']), 2); ?></td>
                            <td><?php echo $discount['start_date'] ? date('M j, Y', strtotime($discount['start_date'])) : 'N/A'; ?></td>
                            <td><?php echo $discount['end_date'] ? date('M j, Y', strtotime($discount['end_date'])) : 'N/A'; ?></td>
                            <td><?php echo $discount['is_active'] ? 'Active' : 'Inactive'; ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
    
    <!-- Current Advertisements -->
    <div class="section-title">
        <h2>Current Advertisements</h2>
    </div>
    
    <?php if (empty($advertisements)): ?>
        <p>No active advertisements found.</p>
    <?php else: ?>
        <div class="cart-table">
            <table>
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Description</th>
                        <th>Position</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($advertisements as $ad): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($ad['title']); ?></td>
                            <td><?php echo htmlspecialchars($ad['description']); ?></td>
                            <td><?php echo htmlspecialchars($ad['position']); ?></td>
                            <td><?php echo $ad['start_date'] ? date('M j, Y', strtotime($ad['start_date'])) : 'N/A'; ?></td>
                            <td><?php echo $ad['end_date'] ? date('M j, Y', strtotime($ad['end_date'])) : 'N/A'; ?></td>
                            <td><?php echo $ad['is_active'] ? 'Active' : 'Inactive'; ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php require_once '../includes/footer.php'; ?>