<?php
include 'db.php';
include 'layout.php';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $reason_name = trim($_POST['reason_name']);
                $description = trim($_POST['description']);
                
                if (!empty($reason_name)) {
                    $stmt = $conn->prepare("INSERT INTO void_reasons (reason_name, description) VALUES (?, ?)");
                    $stmt->bind_param("ss", $reason_name, $description);
                    $stmt->execute();
                    
                    if ($stmt->affected_rows > 0) {
                        $success_message = "Void reason added successfully!";
                    } else {
                        $error_message = "Failed to add void reason.";
                    }
                } else {
                    $error_message = "Reason name is required.";
                }
                break;
                
            case 'update':
                $id = $_POST['id'];
                $reason_name = trim($_POST['reason_name']);
                $description = trim($_POST['description']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!empty($reason_name)) {
                    $stmt = $conn->prepare("UPDATE void_reasons SET reason_name = ?, description = ?, is_active = ? WHERE id = ?");
                    $stmt->bind_param("ssii", $reason_name, $description, $is_active, $id);
                    $stmt->execute();
                    
                    if ($stmt->affected_rows >= 0) {
                        $success_message = "Void reason updated successfully!";
                    } else {
                        $error_message = "Failed to update void reason.";
                    }
                } else {
                    $error_message = "Reason name is required.";
                }
                break;
                
            case 'delete':
                $id = $_POST['id'];
                $stmt = $conn->prepare("DELETE FROM void_reasons WHERE id = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
                
                if ($stmt->affected_rows > 0) {
                    $success_message = "Void reason deleted successfully!";
                } else {
                    $error_message = "Failed to delete void reason.";
                }
                break;
        }
    }
}

// Get all void reasons
$void_reasons = $conn->query("SELECT * FROM void_reasons ORDER BY reason_name");
?>

<div class="page-wrapper">
    <div class="content container-fluid">
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col">
                    <h3 class="page-title">Void Reasons Management</h3>
                    <ul class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                        <li class="breadcrumb-item active">Void Reasons</li>
                    </ul>
                </div>
                <div class="col-auto text-end float-end ms-auto">
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addVoidReasonModal">
                        <i data-feather="plus"></i> Add New Reason
                    </button>
                </div>
            </div>
        </div>

        <?php if (isset($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?= htmlspecialchars($success_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?= htmlspecialchars($error_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-sm-12">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Reason Name</th>
                                        <th>Description</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($reason = $void_reasons->fetch_assoc()): ?>
                                        <tr>
                                            <td><?= $reason['id'] ?></td>
                                            <td><?= htmlspecialchars($reason['reason_name']) ?></td>
                                            <td><?= htmlspecialchars($reason['description'] ?? '') ?></td>
                                            <td>
                                                <span class="badge bg-<?= $reason['is_active'] ? 'success' : 'danger' ?>">
                                                    <?= $reason['is_active'] ? 'Active' : 'Inactive' ?>
                                                </span>
                                            </td>
                                            <td><?= date('M d, Y', strtotime($reason['created_at'])) ?></td>
                                            <td>
                                                <button class="btn btn-sm btn-primary" onclick="editReason(<?= $reason['id'] ?>, '<?= htmlspecialchars($reason['reason_name']) ?>', '<?= htmlspecialchars($reason['description'] ?? '') ?>', <?= $reason['is_active'] ?>)">
                                                    <i data-feather="edit-2"></i>
                                                </button>
                                                <button class="btn btn-sm btn-danger" onclick="deleteReason(<?= $reason['id'] ?>, '<?= htmlspecialchars($reason['reason_name']) ?>')">
                                                    <i data-feather="trash-2"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Void Reason Modal -->
<div class="modal fade" id="addVoidReasonModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Void Reason</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label for="reason_name" class="form-label">Reason Name *</label>
                        <input type="text" class="form-control" id="reason_name" name="reason_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </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 Reason</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Void Reason Modal -->
<div class="modal fade" id="editVoidReasonModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Void Reason</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="mb-3">
                        <label for="edit_reason_name" class="form-label">Reason Name *</label>
                        <input type="text" class="form-control" id="edit_reason_name" name="reason_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_description" class="form-label">Description</label>
                        <textarea class="form-control" id="edit_description" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <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 class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Reason</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editReason(id, name, description, isActive) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_reason_name').value = name;
    document.getElementById('edit_description').value = description;
    document.getElementById('edit_is_active').checked = isActive;
    
    const modal = new bootstrap.Modal(document.getElementById('editVoidReasonModal'));
    modal.show();
}

function deleteReason(id, name) {
    if (confirm(`Are you sure you want to delete the void reason "${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>
