<?php
include("layout.php");
include("db.php");


$error = '';
$success = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $discount_name = trim($_POST['discount_name']);
        $discount_code = trim($_POST['discount_code']);
        $discount_type = $_POST['discount_type'];
        $discount_rate = floatval($_POST['discount_rate']);
        $discount_cap = !empty($_POST['discount_cap']) ? floatval($_POST['discount_cap']) : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (!$discount_name || !$discount_code || !$discount_rate) {
            $error = "Please fill all required fields.";
        } else {
            $stmt = $conn->prepare("INSERT INTO discounts (discount_name, discount_code, discount_type, discount_rate, discount_cap, is_active) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssddi", $discount_name, $discount_code, $discount_type, $discount_rate, $discount_cap, $is_active);
            
            if ($stmt->execute()) {
                $success = "Discount added successfully.";
            } else {
                $error = "Error adding discount: " . $stmt->error;
            }
            $stmt->close();
        }
    }
    
    elseif ($action === 'update') {
        $id = intval($_POST['id']);
        $discount_name = trim($_POST['discount_name']);
        $discount_code = trim($_POST['discount_code']);
        $discount_type = $_POST['discount_type'];
        $discount_rate = floatval($_POST['discount_rate']);
        $discount_cap = !empty($_POST['discount_cap']) ? floatval($_POST['discount_cap']) : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (!$discount_name || !$discount_code || !$discount_rate) {
            $error = "Please fill all required fields.";
        } else {
            $stmt = $conn->prepare("UPDATE discounts SET discount_name = ?, discount_code = ?, discount_type = ?, discount_rate = ?, discount_cap = ?, is_active = ? WHERE id = ?");
            $stmt->bind_param("sssddii", $discount_name, $discount_code, $discount_type, $discount_rate, $discount_cap, $is_active, $id);
            
            if ($stmt->execute()) {
                $success = "Discount updated successfully.";
            } else {
                $error = "Error updating discount: " . $stmt->error;
            }
            $stmt->close();
        }
    }
    
    elseif ($action === 'delete') {
        $id = intval($_POST['id']);
        $stmt = $conn->prepare("DELETE FROM discounts WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            $success = "Discount deleted successfully.";
        } else {
            $error = "Error deleting discount: " . $stmt->error;
        }
        $stmt->close();
    }
}

// Fetch all discounts
$discounts_result = $conn->query("SELECT * FROM discounts ORDER BY created_at DESC");
$discounts = [];
while ($row = $discounts_result->fetch_assoc()) {
    $discounts[] = $row;
}
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="page-title">
                <h4>Discount Management</h4>
                <h6>Manage discount codes and rates</h6>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <!-- Add New Discount Button -->
        <div class="mb-3">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="fas fa-plus"></i> Add New Discount
            </button>
        </div>

        <!-- Discounts List -->
        <div class="card">
            <div class="card-header">
                <h5>Discounts List</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Discount Name</th>
                                <th>Code</th>
                                <th>Type</th>
                                <th>Rate</th>
                                <th>Cap</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($discounts as $discount): ?>
                            <tr>
                                <td><?= $discount['id'] ?></td>
                                <td><strong><?= htmlspecialchars($discount['discount_name']) ?></strong></td>
                                <td><code><?= htmlspecialchars($discount['discount_code']) ?></code></td>
                                <td>
                                    <span class="badge bg-<?= $discount['discount_type'] == 'percentage' ? 'info' : 'warning' ?>">
                                        <?= ucfirst($discount['discount_type']) ?>
                                    </span>
                                </td>
                                <td><?= number_format($discount['discount_rate'], 2) ?><?= $discount['discount_type'] == 'percentage' ? '%' : ' Rs' ?></td>
                                <td><?= $discount['discount_cap'] ? number_format($discount['discount_cap'], 2) . ' Rs' : 'No Cap' ?></td>
                                <td>
                                    <span class="badge bg-<?= $discount['is_active'] ? 'success' : 'secondary' ?>">
                                        <?= $discount['is_active'] ? 'Active' : 'Inactive' ?>
                                    </span>
                                </td>
                                <td><?= date('M d, Y', strtotime($discount['created_at'])) ?></td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="editDiscount(<?= htmlspecialchars(json_encode($discount)) ?>)">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteDiscount(<?= $discount['id'] ?>, '<?= htmlspecialchars($discount['discount_name']) ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Discount</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="add_discount_name" class="form-label">Discount Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="add_discount_name" name="discount_name" required placeholder="10% Off">
                        </div>
                        <div class="col-md-6">
                            <label for="add_discount_code" class="form-label">Discount Code <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="add_discount_code" name="discount_code" required placeholder="DISCOUNT10">
                        </div>
                        <div class="col-md-6">
                            <label for="add_discount_type" class="form-label">Discount Type <span class="text-danger">*</span></label>
                            <select class="form-select" id="add_discount_type" name="discount_type" required>
                                <option value="">Select Type</option>
                                <option value="percentage">Percentage</option>
                                <option value="fixed">Fixed Amount</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="add_discount_rate" class="form-label">Discount Rate <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" class="form-control" id="add_discount_rate" name="discount_rate" required placeholder="10.00">
                        </div>
                        <div class="col-md-6">
                            <label for="add_discount_cap" class="form-label">Discount Cap (Optional)</label>
                            <input type="number" step="0.01" class="form-control" id="add_discount_cap" name="discount_cap" placeholder="500.00">
                            <small class="form-text text-muted">Maximum discount amount (leave empty for no cap)</small>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="add_is_active" name="is_active" checked>
                                <label class="form-check-label" for="add_is_active">Active</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Discount</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="editForm">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" id="edit_id">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Discount</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="edit_discount_name" class="form-label">Discount Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="edit_discount_name" name="discount_name" required>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_discount_code" class="form-label">Discount Code <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="edit_discount_code" name="discount_code" required>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_discount_type" class="form-label">Discount Type <span class="text-danger">*</span></label>
                            <select class="form-select" id="edit_discount_type" name="discount_type" required>
                                <option value="">Select Type</option>
                                <option value="percentage">Percentage</option>
                                <option value="fixed">Fixed Amount</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_discount_rate" class="form-label">Discount Rate <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" class="form-control" id="edit_discount_rate" name="discount_rate" required>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_discount_cap" class="form-label">Discount Cap (Optional)</label>
                            <input type="number" step="0.01" class="form-control" id="edit_discount_cap" name="discount_cap">
                            <small class="form-text text-muted">Maximum discount amount (leave empty for no cap)</small>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="edit_is_active" name="is_active">
                                <label class="form-check-label" for="edit_is_active">Active</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Discount</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editDiscount(discount) {
    document.getElementById('edit_id').value = discount.id;
    document.getElementById('edit_discount_name').value = discount.discount_name;
    document.getElementById('edit_discount_code').value = discount.discount_code;
    document.getElementById('edit_discount_type').value = discount.discount_type;
    document.getElementById('edit_discount_rate').value = discount.discount_rate;
    document.getElementById('edit_discount_cap').value = discount.discount_cap || '';
    document.getElementById('edit_is_active').checked = discount.is_active == 1;
    
    const modal = new bootstrap.Modal(document.getElementById('editModal'));
    modal.show();
}

function deleteDiscount(id, name) {
    if (confirm(`Are you sure you want to delete the discount "${name}"?`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>
