<?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();
?>

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

                    <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">Smart EDI Member Deactivation</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: ?>
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <h5 class="fs-15 mb-4">Single Member Deactivation</h5>
                                            <form id="singleDeactivationForm">
                                                <div class="mb-3">
                                                    <label class="form-label">Member Number</label>
                                                    <input type="text" class="form-control" name="integMemberNumber" required>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Deactivation Reason</label>
                                                    <select class="form-select" name="changeReason" required>
                                                        <option value="">Select Reason</option>
                                                        <option value="RESIGNED">Member Resigned</option>
                                                        <option value="TERMINATED">Contract Terminated</option>
                                                        <option value="TRANSFERRED">Member Transferred</option>
                                                        <option value="POLICY_END">Policy Ended</option>
                                                        <option value="DECEASED">Member Deceased</option>
                                                        <option value="OTHER">Other Reason</option>
                                                    </select>
                                                </div>

                                                <div class="mb-3" id="otherReasonDiv" style="display: none;">
                                                    <label class="form-label">Specify Other Reason</label>
                                                    <textarea class="form-control" name="otherReason" rows="2"></textarea>
                                                </div>

                                                <button type="submit" class="btn btn-danger">
                                                    <i class="ri-user-unfollow-line align-middle me-1"></i>
                                                    Deactivate Member
                                                </button>
                                            </form>
                                        </div>

                                        <div class="col-lg-6">
                                            <h5 class="fs-15 mb-4">Bulk Member Deactivation</h5>
                                            <form id="bulkDeactivationForm">
                                                <div class="mb-3">
                                                    <label class="form-label">Upload CSV</label>
                                                    <input type="file" class="form-control" name="csvFile" accept=".csv" required>
                                                    <small class="text-muted">CSV should have member_number and deactivation_reason columns</small>
                                                </div>

                                                <div class="mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="skipErrors" id="skipErrors">
                                                        <label class="form-check-label" for="skipErrors">
                                                            Skip errors and continue processing
                                                        </label>
                                                    </div>
                                                </div>

                                                <button type="submit" class="btn btn-danger">
                                                    <i class="ri-upload-2-line align-middle me-1"></i>
                                                    Upload and Process
                                                </button>

                                                <a href="download_deactivation_template.php" class="btn btn-light ms-2">
                                                    <i class="ri-download-2-line align-middle me-1"></i>
                                                    Download Template
                                                </a>
                                            </form>
                                        </div>
                                    </div>

                                    <!-- Progress Bar -->
                                    <div class="progress mt-4" style="height: 25px; display: none;" id="progressBar">
                                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-danger" 
                                             role="progressbar" style="width: 0%">
                                            Processing...
                                        </div>
                                    </div>

                                    <!-- Results Table -->
                                    <div class="mt-4" id="resultArea" style="display: none;">
                                        <h5>Processing Results</h5>
                                        <div class="table-responsive">
                                            <table class="table table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Member Number</th>
                                                        <th>Status</th>
                                                        <th>Message</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="resultTable">
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <?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>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const singleForm = document.getElementById('singleDeactivationForm');
        const bulkForm = document.getElementById('bulkDeactivationForm');
        const reasonSelect = document.querySelector('select[name="changeReason"]');
        const otherReasonDiv = document.getElementById('otherReasonDiv');
        const progressBar = document.getElementById('progressBar');
        const progressBarInner = progressBar.querySelector('.progress-bar');
        const resultArea = document.getElementById('resultArea');
        const resultTable = document.getElementById('resultTable');

        // Show/hide other reason textarea
        reasonSelect?.addEventListener('change', function() {
            otherReasonDiv.style.display = this.value === 'OTHER' ? 'block' : 'none';
            if (this.value !== 'OTHER') {
                otherReasonDiv.querySelector('textarea').value = '';
            }
        });

        // Single member deactivation
        singleForm?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(singleForm);
            if (reasonSelect.value === 'OTHER') {
                formData.set('changeReason', formData.get('otherReason'));
            }
            formData.append('countryCode', '<?php echo $provider['country_code']; ?>');

            Swal.fire({
                title: 'Confirm Deactivation',
                text: 'Are you sure you want to deactivate this member?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Deactivate',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#d33'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Deactivating Member',
                        text: 'Please wait...',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    fetch('deactivate_edi_member.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (!data.success) {
                            throw new Error(data.error || 'Failed to deactivate member');
                        }

                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: 'Member deactivated successfully'
                        }).then(() => {
                            singleForm.reset();
                            otherReasonDiv.style.display = 'none';
                        });
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: error.message
                        });
                    });
                }
            });
        });

        // Bulk member deactivation
        bulkForm?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(bulkForm);
            formData.append('countryCode', '<?php echo $provider['country_code']; ?>');

            Swal.fire({
                title: 'Confirm Bulk Deactivation',
                text: 'Are you sure you want to process bulk member deactivations?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Process',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#d33'
            }).then((result) => {
                if (result.isConfirmed) {
                    progressBar.style.display = 'block';
                    progressBarInner.style.width = '0%';
                    progressBarInner.textContent = 'Processing...';
                    resultArea.style.display = 'none';
                    resultTable.innerHTML = '';

                    fetch('process_bulk_deactivation.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (!data.success) {
                            throw new Error(data.error || 'Failed to process file');
                        }

                        let processed = 0;
                        const total = data.members.length;
                        
                        data.members.forEach(member => {
                            const row = document.createElement('tr');
                            const statusClass = member.success ? 'success' : 'danger';
                            row.innerHTML = `
                                <td>${member.member_number}</td>
                                <td><span class="badge bg-${statusClass}">
                                    ${member.success ? 'Success' : 'Failed'}
                                </span></td>
                                <td>${member.message}</td>
                            `;
                            resultTable.appendChild(row);
                            
                            processed++;
                            const percent = Math.round((processed / total) * 100);
                            progressBarInner.style.width = `${percent}%`;
                            progressBarInner.textContent = `Processing ${processed} of ${total}`;
                        });

                        resultArea.style.display = 'block';

                        if (processed === total) {
                            const successCount = data.members.filter(m => m.success).length;
                            Swal.fire({
                                icon: successCount === total ? 'success' : 'warning',
                                title: 'Processing Complete',
                                html: `
                                    Successfully deactivated ${successCount} of ${total} members<br>
                                    ${successCount < total ? 'See results table for details' : ''}
                                `
                            });
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: error.message
                        });
                    })
                    .finally(() => {
                        progressBar.style.display = 'none';
                    });
                }
            });
        });
    });
    </script>
</body>
</html>