<?php
session_start();
include('db.php'); // Your database connection

// Check if the admin is logged in
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}

// Array mapping operator IDs to names
$operators = [
    1 => 'Grameenphone',
    2 => 'Banglalink',
    3 => 'Robi',
    4 => 'Airtel',
    5 => 'Teletalk'
];

// Fetch all offers
$offersQuery = "SELECT * FROM offers";
$offersResult = $conn->query($offersQuery);

// Add new offer
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['addOffer'])) {
    $operatorId = $_POST['operator_id'];
    $offerName = $_POST['offer_name'];
    $validity = $_POST['validity'];
    $price = $_POST['price'];

    // Insert the new offer into the database
    $insertQuery = "INSERT INTO offers (operator_id, offer_name, validity, price) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($insertQuery);
    $stmt->bind_param('issd', $operatorId, $offerName, $validity, $price);
    $stmt->execute();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Update offer
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['editOfferId'])) {
    $offerId = $_POST['editOfferId'];
    $operatorId = $_POST['editOperatorId'];
    $offerName = $_POST['editOfferName'];
    $validity = $_POST['editValidity'];
    $price = $_POST['editPrice'];

    // Update the offer in the database
    $updateQuery = "UPDATE offers SET operator_id = ?, offer_name = ?, validity = ?, price = ? WHERE id = ?";
    $stmt = $conn->prepare($updateQuery);
    $stmt->bind_param('issdi', $operatorId, $offerName, $validity, $price, $offerId);
    $stmt->execute();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Delete offer
if (isset($_GET['delete'])) {
    $offerId = $_GET['delete'];
    $deleteQuery = "DELETE FROM offers WHERE id = ?";
    $stmt = $conn->prepare($deleteQuery);
    $stmt->bind_param('i', $offerId);
    $stmt->execute();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel - Offers</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 80%;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        .edit-btn, .delete-btn, .add-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .edit-btn {
            background-color: #4CAF50;
            color: white;
        }
        .delete-btn {
            background-color: #f44336;
            color: white;
        }
        .add-btn {
            background-color: #2196F3;
            color: white;
            margin-bottom: 20px;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            padding-top: 100px;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            overflow: auto;
        }
        .modal-content {
            background-color: #fff;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 50%;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover, .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
        .save-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>

    <div class="container">
        <h2>Admin Panel - Offers</h2>

        <button class="add-btn" onclick="showAddModal()">Add New Offer</button>
        
        <table>
            <tr>
                <th>#</th>
                <th>Operator</th>
                <th>Offer Name</th>
                <th>Validity</th>
                <th>Price</th>
                <th>Action</th>
            </tr>
            <?php if ($offersResult->num_rows > 0): ?>
                <?php while($offer = $offersResult->fetch_assoc()): ?>
                <tr>
                    <td><?php echo $offer['id']; ?></td>
                    <td><?php echo $operators[$offer['operator_id']] ?? 'Unknown'; ?></td>
                    <td><?php echo htmlspecialchars($offer['offer_name']); ?></td>
                    <td><?php echo htmlspecialchars($offer['validity']); ?></td>
                    <td><?php echo number_format($offer['price'], 2); ?></td>
                    <td>
                        <div class="action-buttons">
                            <button class="edit-btn" onclick="showEditModal('<?php echo $offer['id']; ?>', '<?php echo $offer['operator_id']; ?>', '<?php echo htmlspecialchars($offer['offer_name']); ?>', '<?php echo htmlspecialchars($offer['validity']); ?>', '<?php echo $offer['price']; ?>')">Edit</button>
                            <a href="?delete=<?php echo $offer['id']; ?>" class="delete-btn" onclick="return confirm('Are you sure you want to delete this offer?')">Delete</a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="6">No offers found.</td>
                </tr>
            <?php endif; ?>
        </table>
    </div>

    <!-- Add Modal -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('addModal')">&times;</span>
            <h3>Add New Offer</h3>
            <form method="POST">
                <div>
                    <label for="operator_id">Operator:</label>
                    <select name="operator_id" required>
                        <?php foreach ($operators as $id => $name): ?>
                            <option value="<?php echo $id; ?>"><?php echo $name; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="offer_name">Offer Name:</label>
                    <input type="text" name="offer_name" required>
                </div>
                <div>
                    <label for="validity">Validity:</label>
                    <input type="text" name="validity">
                </div>
                <div>
                    <label for="price">Price:</label>
                    <input type="number" name="price" step="0.01" required>
                </div>
                <button type="submit" class="save-btn" name="addOffer">Add Offer</button>
            </form>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('editModal')">&times;</span>
            <h3>Edit Offer</h3>
            <form method="POST">
                <input type="hidden" name="editOfferId" id="editOfferId">
                <div>
                    <label for="editOperatorId">Operator:</label>
                    <select name="editOperatorId" id="editOperatorId" required>
                        <?php foreach ($operators as $id => $name): ?>
                            <option value="<?php echo $id; ?>"><?php echo $name; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="editOfferName">Offer Name:</label>
                    <input type="text" name="editOfferName" id="editOfferName" required>
                </div>
                <div>
                    <label for="editValidity">Validity:</label>
                    <input type="text" name="editValidity" id="editValidity">
                </div>
                <div>
                    <label for="editPrice">Price:</label>
                    <input type="number" name="editPrice" id="editPrice" step="0.01" required>
                </div>
                <button type="submit" class="save-btn">Save Changes</button>
            </form>
        </div>
    </div>

    <script>
        // Show Add Modal
        function showAddModal() {
            document.getElementById('addModal').style.display = 'block';
        }

        // Show Edit Modal
        function showEditModal(id, operatorId, offerName, validity, price) {
            document.getElementById('editOfferId').value = id;
            document.getElementById('editOperatorId').value = operatorId;
            document.getElementById('editOfferName').value = offerName;
            document.getElementById('editValidity').value = validity;
            document.getElementById('editPrice').value = price;
            document.getElementById('editModal').style.display = 'block';
        }

        // Close Modal
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
    </script>

</body>
</html>
