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

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Get Smart EDI configuration
$sql = "SELECT p.*, c.* FROM edi_providers p 
        JOIN edi_configurations c ON p.provider_id = c.provider_id
        WHERE p.edi_type = 'SMART' AND p.is_active = 1 
        AND p.status = 'CONFIGURED'";
$result = $conn->query($sql);
$provider = $result->fetch_assoc();

// Get list of schemes
$sql = "SELECT corp_id, corporate, scheme FROM corporate WHERE cancelled = 0 ORDER BY corporate";
$result = $conn->query($sql);
$schemes = $result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Suspend Benefits')); ?>
    <?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' => 'EDI', 'title' => 'Suspend Benefits')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Suspend Benefits</h4>
                                </div>
                                
                                <div class="card-body">
                                    <?php if (!$provider): ?>
                                    <div class="alert alert-danger">
                                        Smart EDI not configured. Please configure the integration first.
                                    </div>
                                    <?php else: ?>

                                    <form id="suspendForm" class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Scheme</label>
                                            <select class="form-select" id="schemeSelect" required>
                                                <option value="">Select Scheme</option>
                                                <?php foreach ($schemes as $scheme): ?>
                                                    <option value="<?php echo $scheme['corp_id']; ?>" 
                                                            data-scheme="<?php echo $scheme['scheme']; ?>">
                                                        <?php echo $scheme['corporate']; ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>

                                        <div class="col-md-4">
                                            <label class="form-label">Category</label>
                                            <select class="form-select" id="categorySelect" disabled required>
                                                <option value="">Select Category</option>
                                            </select>
                                        </div>

                                        <div class="col-md-4">
                                            <label class="form-label">Benefit</label>
                                            <select class="form-select" id="benefitSelect" disabled required>
                                                <option value="">Select Benefit</option>
                                            </select>
                                        </div>

                                        <div class="col-12">
                                            <label class="form-label">Suspension Reason</label>
                                            <textarea class="form-control" id="suspendReason" rows="3" required
                                                      placeholder="Enter reason for suspending the benefit"></textarea>
                                        </div>

                                        <div class="col-12">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-stop-circle-line align-middle me-1"></i>
                                                Suspend Benefit
                                            </button>
                                        </div>
                                    </form>

                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        $('#schemeSelect').on('change', function() {
            const schemeId = $(this).val();
            if (schemeId) {
                fetchCategories(schemeId);
                $('#categorySelect').prop('disabled', false);
            } else {
                $('#categorySelect').prop('disabled', true).empty().append('<option value="">Select Category</option>');
                $('#benefitSelect').prop('disabled', true).empty().append('<option value="">Select Benefit</option>');
            }
        });

        $('#categorySelect').on('change', function() {
            const categoryId = $(this).val();
            if (categoryId) {
                fetchBenefits(categoryId);
                $('#benefitSelect').prop('disabled', false);
            } else {
                $('#benefitSelect').prop('disabled', true).empty().append('<option value="">Select Benefit</option>');
            }
        });

        $('#suspendForm').on('submit', function(e) {
            e.preventDefault();
            
            const data = {
                corp_id: $('#schemeSelect').val(),
                category_code: $('#categorySelect').val(),
                benefit_code: $('#benefitSelect').val(),
                reason: $('#suspendReason').val()
            };

            Swal.fire({
                title: 'Confirm Suspension',
                text: 'Are you sure you want to suspend this benefit?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Suspend Benefit',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    suspendBenefit(data);
                }
            });
        });
    });

    function suspendBenefit(data) {
        Swal.fire({
            title: 'Processing...',
            text: 'Please wait while we suspend the benefit',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        fetch('suspend_benefit.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'Benefit suspended successfully'
                }).then(() => {
                    window.location.reload();
                });
            } else {
                throw new Error(result.error || 'Failed to suspend benefit');
            }
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message
            });
        });
    }

    function fetchCategories(schemeId) {
        fetch(`get_categories.php?scheme_id=${schemeId}`)
            .then(response => response.json())
            .then(data => {
                const select = $('#categorySelect');
                select.empty().append('<option value="">Select Category</option>');
                data.categories.forEach(category => {
                    select.append(`<option value="${category.clnCatCode}">${category.catDesc}</option>`);
                });
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to fetch categories'
                });
            });
    }

    function fetchBenefits(categoryId) {
        const schemeId = $('#schemeSelect').val();
        fetch(`get_bene.php?scheme_id=${schemeId}&category_id=${categoryId}`)
            .then(response => response.json())
            .then(data => {
                const select = $('#benefitSelect');
                select.empty().append('<option value="">Select Benefit</option>');
                data.benefits.forEach(benefit => {
                    select.append(`<option value="${benefit.clnBenCode}">${benefit.benefitDesc}</option>`);
                });
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to fetch benefits'
                });
            });
    }
    </script>
</body>
</html>