<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Function to get the last code for benefits
function getLastBenefitCode($conn) {
    $result = $conn->query("SELECT MAX(CAST(code AS UNSIGNED)) as last_code FROM benefit");
    $row = $result->fetch_assoc();
    return $row['last_code'] ? sprintf('%03d', $row['last_code']) : '000';
}

// Function to get the last code for services
function getLastServiceCode($conn) {
    $result = $conn->query("SELECT MAX(CAST(code AS UNSIGNED)) as last_code FROM services");
    $row = $result->fetch_assoc();
    return $row['last_code'] ? sprintf('%03d', $row['last_code']) : '000';
}

// Function to get the last code for providers
function getLastProviderCode($conn) {
    $result = $conn->query("SELECT MAX(CAST(provider_code AS UNSIGNED)) as last_code FROM providers WHERE provider_code REGEXP '^[0-9]+$'");
    $row = $result->fetch_assoc();
    return $row['last_code'] ? sprintf('%03d', $row['last_code']) : '000';
}

// Function to generate the next code
function generateNextCode($lastCode) {
    return sprintf('%03d', intval($lastCode) + 1);
}

// Function to get corporate groups
function getCorporateGroups($conn) {
    $result = $conn->query("SELECT cg.*, 
                           COUNT(cgr.idx) as total_benefits,
                           GROUP_CONCAT(DISTINCT b.benefit) as benefit_names
                           FROM corporate_groups cg
                           LEFT JOIN corp_groups cgr ON cg.group_code = cgr.category COLLATE utf8mb4_general_ci
                           LEFT JOIN benefit b ON cgr.benefit = b.code COLLATE utf8mb4_general_ci
                           WHERE cg.status = 1
                           GROUP BY cg.group_id
                           ORDER BY cg.group_name");
    $groups = [];
    while ($row = $result->fetch_assoc()) {
        $groups[] = $row;
    }
    return $groups;
}

// Function to get group benefits
function getGroupBenefits($conn, $group_code) {
    $stmt = $conn->prepare("SELECT cgr.*, b.benefit 
                           FROM corp_groups cgr
                           JOIN benefit b ON cgr.benefit = b.code COLLATE utf8mb4_general_ci
                           WHERE cgr.category = ? COLLATE utf8mb4_general_ci
                           ORDER BY b.benefit");
    $stmt->bind_param('s', $group_code);
    $stmt->execute();
    $result = $stmt->get_result();
    $benefits = [];
    while ($row = $result->fetch_assoc()) {
        $benefits[] = $row;
    }
    return $benefits;
}

// Function to get all available benefits
function getAllBenefits($conn) {
    $result = $conn->query("SELECT code, benefit FROM benefit ORDER BY benefit");
    $benefits = [];
    while ($row = $result->fetch_assoc()) {
        $benefits[] = $row;
    }
    return $benefits;
}

// Initialize response array
$response = ['success' => false, 'message' => ''];

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['add_benefit'])) {
            if (empty($_POST['benefit_name']) || empty($_POST['benefit_code'])) {
                throw new Exception('Benefit name and code are required');
            }
            $stmt = $conn->prepare("INSERT INTO benefit (code, benefit) VALUES (?, ?)");
            $stmt->bind_param('ss', $_POST['benefit_code'], $_POST['benefit_name']);
            if ($stmt->execute()) {
                $response = ['success' => true, 'message' => 'Benefit added successfully'];
            }
        }
        
        if (isset($_POST['add_service'])) {
            if (empty($_POST['service']) || empty($_POST['code'])) {
                throw new Exception('Service name and code are required');
            }
            $stmt = $conn->prepare("INSERT INTO services (service, code, status) VALUES (?, ?, 1)");
            $stmt->bind_param('ss', $_POST['service'], $_POST['code']);
            if ($stmt->execute()) {
                $response = ['success' => true, 'message' => 'Service added successfully'];
            }
        }
        
        if (isset($_POST['add_provider'])) {
            if (empty($_POST['provider_name']) || empty($_POST['provider_code'])) {
                throw new Exception('Provider name and code are required');
            }
            $stmt = $conn->prepare("INSERT INTO providers (provider_name, provider_code, tel_no, email, status) VALUES (?, ?, ?, ?, 1)");
            $stmt->bind_param('ssss', $_POST['provider_name'], $_POST['provider_code'], $_POST['tel_no'], $_POST['email']);
            if ($stmt->execute()) {
                $response = ['success' => true, 'message' => 'Provider added successfully'];
            } else {
                throw new Exception('Failed to add provider');
            }
        }
        
        if (isset($_POST['update_corporate_group'])) {
            $group_id = $_POST['group_id'];
            $group_name = $_POST['group_name'];
            $group_code = $_POST['group_code'];
            $description = $_POST['description'];
            $benefits = isset($_POST['benefits']) ? $_POST['benefits'] : [];
            $limits = isset($_POST['limits']) ? $_POST['limits'] : [];
            $sharing = isset($_POST['sharing']) ? $_POST['sharing'] : [];
            $fund = isset($_POST['fund']) ? $_POST['fund'] : [];
            
            $stmt = $conn->prepare("UPDATE corporate_groups 
                                  SET group_name = ?, group_code = ?, description = ?, 
                                      modified_by = ?, modified_at = CURRENT_TIMESTAMP
                                  WHERE group_id = ?");
            $stmt->bind_param('sssii', $group_name, $group_code, $description, 
                             $_SESSION['user_id'], $group_id);
            $stmt->execute();
            
            $stmt = $conn->prepare("DELETE FROM corp_groups WHERE category = ?");
            $stmt->bind_param('s', $group_code);
            $stmt->execute();
            
            if (!empty($benefits)) {
                $stmt = $conn->prepare("INSERT INTO corp_groups 
                                      (category, benefit, `limit`, sharing, fund) 
                                      VALUES (?, ?, ?, ?, ?)");
                foreach ($benefits as $index => $benefit_code) {
                    $limit = $limits[$index] ?? 0;
                    $is_sharing = isset($sharing[$index]) ? 1 : 0;
                    $is_fund = isset($fund[$index]) ? 1 : 0;
                    $stmt->bind_param('siddi', $group_code, $benefit_code, $limit, 
                                    $is_sharing, $is_fund);
                    $stmt->execute();
                }
            }
            $response = ['success' => true, 'message' => 'Corporate group updated successfully'];
        }
    } catch (Exception $e) {
        $response['message'] = $e->getMessage();
    }
}

// Get the next codes for each entity after processing form submissions
$nextBenefitCode = generateNextCode(getLastBenefitCode($conn));
$nextServiceCode = generateNextCode(getLastServiceCode($conn));
$nextProviderCode = generateNextCode(getLastProviderCode($conn));

// Fetch existing records
$benefits = $conn->query("SELECT * FROM benefit ORDER BY code");
$services = $conn->query("SELECT * FROM services WHERE status = 1 ORDER BY code");
$providers = $conn->query("SELECT * FROM providers WHERE status = 1 ORDER BY provider_id");

// Fetch corporate groups and benefits
$corporateGroups = getCorporateGroups($conn);
$allBenefits = getAllBenefits($conn);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'System Settings')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Settings', 'title' => 'System Settings')); ?>

                    <!-- Notification for form submission -->
                    <?php if (!empty($response['message'])): ?>
                        <div class="alert alert-<?php echo $response['success'] ? 'success' : 'danger'; ?> alert-dismissible fade show">
                            <?php echo $response['message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Benefits Section -->
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Benefits</h4>
                                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addBenefitModal">
                                        <i class="ri-add-line align-middle"></i> Add Benefit
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Code</th>
                                                    <th>Benefit Name</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($benefit = $benefits->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo $benefit['code']; ?></td>
                                                    <td><?php echo htmlspecialchars($benefit['benefit']); ?></td>
                                                    <td>
                                                        <div class="hstack gap-2">
                                                            <button class="btn btn-sm btn-info edit-benefit" 
                                                                    data-id="<?php echo $benefit['code']; ?>"
                                                                    data-name="<?php echo htmlspecialchars($benefit['benefit']); ?>">
                                                                <i class="ri-pencil-line"></i>
                                                            </button>
                                                            <button class="btn btn-sm btn-danger delete-benefit"
                                                                    data-id="<?php echo $benefit['code']; ?>">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Services Section -->
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Services</h4>
                                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addServiceModal">
                                        <i class="ri-add-line align-middle"></i> Add Service
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Code</th>
                                                    <th>Service Name</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($service = $services->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($service['code']); ?></td>
                                                    <td><?php echo htmlspecialchars($service['service']); ?></td>
                                                    <td>
                                                        <div class="hstack gap-2">
                                                            <button class="btn btn-sm btn-info edit-service"
                                                                    data-id="<?php echo $service['code']; ?>"
                                                                    data-name="<?php echo htmlspecialchars($service['service']); ?>"
                                                                    data-code="<?php echo htmlspecialchars($service['code']); ?>">
                                                                <i class="ri-pencil-line"></i>
                                                            </button>
                                                            <button class="btn btn-sm btn-danger delete-service"
                                                                    data-id="<?php echo $service['code']; ?>">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Providers Section -->
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Providers</h4>
                                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addProviderModal">
                                        <i class="ri-add-line align-middle"></i> Add Provider
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Code</th>
                                                    <th>Provider Name</th>
                                                    <th>Contact</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($provider = $providers->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($provider['provider_code']); ?></td>
                                                    <td><?php echo htmlspecialchars($provider['provider_name']); ?></td>
                                                    <td>
                                                        <?php echo htmlspecialchars($provider['tel_no']); ?><br>
                                                        <small><?php echo htmlspecialchars($provider['email']); ?></small>
                                                    </td>
                                                    <td>
                                                        <div class="hstack gap-2">
                                                            <button class="btn btn-sm btn-info edit-provider"
                                                                    data-id="<?php echo $provider['provider_id']; ?>"
                                                                    data-name="<?php echo htmlspecialchars($provider['provider_name']); ?>"
                                                                    data-code="<?php echo htmlspecialchars($provider['provider_code']); ?>"
                                                                    data-tel="<?php echo htmlspecialchars($provider['tel_no']); ?>"
                                                                    data-email="<?php echo htmlspecialchars($provider['email']); ?>">
                                                                <i class="ri-pencil-line"></i>
                                                            </button>
                                                            <button class="btn btn-sm btn-danger delete-provider"
                                                                    data-id="<?php echo $provider['provider_id']; ?>">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Corporate Groups Section -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Corporate Groups</h4>
                                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addGroupModal">
                                        <i class="ri-add-line align-middle"></i> Add Group
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Group Code</th>
                                                    <th>Group Name</th>
                                                    <th>Description</th>
                                                    <th>Benefits</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($corporateGroups as $group): 
                                                    $groupBenefits = getGroupBenefits($conn, $group['group_code']);
                                                ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($group['group_code']); ?></td>
                                                    <td><?php echo htmlspecialchars($group['group_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($group['description'] ?? ''); ?></td>
                                                    <td>
                                                        <?php 
                                                        $benefitDetails = [];
                                                        foreach ($groupBenefits as $benefit) {
                                                            $details = htmlspecialchars($benefit['benefit']);
                                                            if ($benefit['limit'] > 0) {
                                                                $details .= ' (Limit: ' . number_format($benefit['limit'], 2) . ')';
                                                            }
                                                            if ($benefit['sharing']) {
                                                                $details .= ' [Sharing]';
                                                            }
                                                            if ($benefit['fund']) {
                                                                $details .= ' [Fund]';
                                                            }
                                                            $benefitDetails[] = $details;
                                                        }
                                                        echo implode('<br>', $benefitDetails);
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <div class="hstack gap-2">
                                                            <button class="btn btn-sm btn-info edit-group"
                                                                    data-id="<?php echo $group['group_id']; ?>"
                                                                    data-code="<?php echo htmlspecialchars($group['group_code']); ?>"
                                                                    data-name="<?php echo htmlspecialchars($group['group_name']); ?>"
                                                                    data-description="<?php echo htmlspecialchars($group['description'] ?? ''); ?>"
                                                                    data-benefits='<?php echo json_encode($groupBenefits); ?>'>
                                                                <i class="ri-pencil-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Benefit Modal -->
    <div class="modal fade" id="addBenefitModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title">Add New Benefit</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Benefit Code</label>
                            <input type="text" class="form-control" name="benefit_code" value="<?php echo $nextBenefitCode; ?>" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Benefit Name</label>
                            <input type="text" class="form-control" name="benefit_name" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                        <button type="submit" name="add_benefit" class="btn btn-primary">Add Benefit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Service Modal -->
    <div class="modal fade" id="addServiceModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title">Add New Service</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Service Code</label>
                            <input type="text" class="form-control" name="code" value="<?php echo $nextServiceCode; ?>" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Service Name</label>
                            <input type="text" class="form-control" name="service" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                        <button type="submit" name="add_service" class="btn btn-primary">Add Service</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Provider Modal -->
    <div class="modal fade" id="addProviderModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title">Add New Provider</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Provider Code</label>
                            <input type="text" class="form-control" name="provider_code" value="<?php echo $nextProviderCode; ?>" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Provider Name</label>
                            <input type="text" class="form-control" name="provider_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Telephone Number</label>
                            <input type="text" class="form-control" name="tel_no" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="email" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                        <button type="submit" name="add_provider" class="btn btn-primary">Add Provider</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Corporate Group Modal -->
    <div class="modal fade" id="editGroupModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title">Edit Corporate Group</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="group_id" id="editGroupId">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Group Code</label>
                                <input type="text" class="form-control" name="group_code" id="editGroupCode" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Group Name</label>
                                <input type="text" class="form-control" name="group_name" id="editGroupName" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="description" id="editDescription" rows="2"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Benefits</label>
                            <div id="benefitsContainer">
                                <!-- Benefits will be added here dynamically -->
                            </div>
                            <button type="button" class="btn btn-sm btn-secondary mt-2" id="addBenefit">
                                <i class="ri-add-line"></i> Add Benefit
                            </button>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                        <button type="submit" name="update_corporate_group" class="btn btn-primary">Update Group</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Edit Benefit
        document.querySelectorAll('.edit-benefit').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.dataset.id;
                const name = this.dataset.name;
                
                Swal.fire({
                    title: 'Edit Benefit',
                    html: `<input type="text" id="editBenefitName" class="swal2-input" value="${name}">`,
                    showCancelButton: true,
                    confirmButtonText: 'Save',
                    preConfirm: () => {
                        return document.getElementById('editBenefitName').value;
                    }
                }).then((result) => {
                    if (result.isConfirmed) {
                        updateBenefit(id, result.value);
                    }
                });
            });
        });

        // Delete Benefit
        document.querySelectorAll('.delete-benefit').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.dataset.id;
                confirmDelete('benefit', id);
            });
        });

        // Edit Service
        document.querySelectorAll('.edit-service').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.dataset.id;
                const name = this.dataset.name;
                const code = this.dataset.code;
                
                Swal.fire({
                    title: 'Edit Service',
                    html: `
                        <input type="text" id="editServiceName" class="swal2-input" value="${name}" placeholder="Service Name">
                        <input type="text" id="editServiceCode" class="swal2-input" value="${code}" placeholder="Service Code">
                    `,
                    showCancelButton: true,
                    confirmButtonText: 'Save',
                    preConfirm: () => ({
                        name: document.getElementById('editServiceName').value,
                        code: document.getElementById('editServiceCode').value
                    })
                }).then((result) => {
                    if (result.isConfirmed) {
                        updateService(id, result.value);
                    }
                });
            });
        });

        // Delete Service
        document.querySelectorAll('.delete-service').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.dataset.id;
                confirmDelete('service', id);
            });
        });

        // Edit Provider
        document.querySelectorAll('.edit-provider').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.dataset.id;
                const name = this.dataset.name;
                const code = this.dataset.code;
                const tel = this.dataset.tel;
                const email = this.dataset.email;
                
                Swal.fire({
                    title: 'Edit Provider',
                    html: `
                        <input type="text" id="editProviderName" class="swal2-input" value="${name}" placeholder="Provider Name">
                        <input type="text" id="editProviderCode" class="swal2-input" value="${code}" placeholder="Provider Code">
                        <input type="text" id="editProviderTel" class="swal2-input" value="${tel}" placeholder="Telephone">
                        <input type="email" id="editProviderEmail" class="swal2-input" value="${email}" placeholder="Email">
                    `,
                    showCancelButton: true,
                    confirmButtonText: 'Save',
                    preConfirm: () => ({
                        name: document.getElementById('editProviderName').value,
                        code: document.getElementById('editProviderCode').value,
                        tel: document.getElementById('editProviderTel').value,
                        email: document.getElementById('editProviderEmail').value
                    })
                }).then((result) => {
                    if (result.isConfirmed) {
                        updateProvider(id, result.value);
                    }
                });
            });
        });

        // Delete Provider
        document.querySelectorAll('.delete-provider').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.dataset.id;
                confirmDelete('provider', id);
            });
        });

        // Helper Functions
        function confirmDelete(type, id) {
            Swal.fire({
                title: 'Are you sure?',
                text: `This ${type} will be deleted permanently!`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'No, cancel!'
            }).then((result) => {
                if (result.isConfirmed) {
                    deleteItem(type, id);
                }
            });
        }

        function updateBenefit(id, name) {
            sendRequest('update_benefit.php', { id, name });
        }

        function updateService(id, data) {
            sendRequest('update_service.php', { id, ...data });
        }

        function updateProvider(id, data) {
            sendRequest('update_provider.php', { id, ...data });
        }

        function deleteItem(type, id) {
            sendRequest(`delete_${type}.php`, { id });
        }

        function sendRequest(url, data) {
            fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const row = document.querySelector(`button[data-id="${data.id}"]`)?.closest('tr');
                    if (row) row.remove();
                    Swal.fire('Success', data.message || 'Operation completed successfully', 'success');
                } else {
                    throw new Error(data.error || 'Operation failed');
                }
            })
            .catch(error => {
                Swal.fire('Error', error.message, 'error');
            });
        }

        // Function to create benefit row
        function createBenefitRow(benefit = null) {
            const row = document.createElement('div');
            row.className = 'benefit-row mb-2';
            row.innerHTML = `
                <div class="row">
                    <div class="col-md-4">
                        <select class="form-select benefit-select" name="benefits[]" required>
                            <option value="">Select Benefit</option>
                            <?php foreach ($allBenefits as $benefit): ?>
                                <option value="<?php echo $benefit['code']; ?>"
                                        ${benefit && benefit['benefit'] === '<?php echo $benefit['code']; ?>' ? 'selected' : ''}>
                                    <?php echo htmlspecialchars($benefit['benefit']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="form-control" name="limits[]" 
                               placeholder="Limit" step="0.01" 
                               value="${benefit ? benefit.limit : ''}">
                    </div>
                    <div class="col-md-2">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="sharing[]" 
                                   ${benefit && benefit.sharing ? 'checked' : ''}>
                            <label class="form-check-label">Sharing</label>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="fund[]" 
                                   ${benefit && benefit.fund ? 'checked' : ''}>
                            <label class="form-check-label">Fund</label>
                        </div>
                    </div>
                    <div class="col-md-1">
                        <button type="button" class="btn btn-sm btn-danger remove-benefit">
                            <i class="ri-delete-bin-line"></i>
                        </button>
                    </div>
                </div>
            `;
            return row;
        }

        // Add benefit button click handler
        document.getElementById('addBenefit')?.addEventListener('click', function() {
            const container = document.getElementById('benefitsContainer');
            container.appendChild(createBenefitRow());
        });

        // Remove benefit button click handler
        document.addEventListener('click', function(e) {
            if (e.target.closest('.remove-benefit')) {
                e.target.closest('.benefit-row').remove();
            }
        });

        // Edit Group button click handler
        document.querySelectorAll('.edit-group').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.dataset.id;
                const code = this.dataset.code;
                const name = this.dataset.name;
                const description = this.dataset.description;
                const benefits = JSON.parse(this.dataset.benefits);
                
                document.getElementById('editGroupId').value = id;
                document.getElementById('editGroupCode').value = code;
                document.getElementById('editGroupName').value = name;
                document.getElementById('editDescription').value = description;
                
                const container = document.getElementById('benefitsContainer');
                container.innerHTML = '';
                benefits.forEach(benefit => {
                    container.appendChild(createBenefitRow(benefit));
                });
                
                new bootstrap.Modal(document.getElementById('editGroupModal')).show();
            });
        });
    });
    </script>
</body>
</html>