<?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 Activation')); ?>
    <?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 Activation')); ?>

                    <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 Activation</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 Activation</h5>
                                            <form id="singleActivationForm">
                                                <div class="mb-3">
                                                    <label class="form-label">Member Number</label>
                                                    <input type="text" class="form-control" name="integMemberNumber" required>
                                                    <small class="text-muted">Enter the member number to activate</small>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Activation Reason</label>
                                                    <textarea class="form-control" name="changeReason" rows="2" required></textarea>
                                                </div>

                                                <button type="submit" class="btn btn-primary">
                                                    <i class="ri-user-follow-line align-middle me-1"></i>
                                                    Activate Member
                                                </button>
                                            </form>
                                        </div>

                                        <div class="col-lg-6">
                                            <h5 class="fs-15 mb-4">Bulk Member Activation</h5>
                                            <form id="bulkActivationForm">
                                                <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 activation_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-primary">
                                                    <i class="ri-upload-2-line align-middle me-1"></i>
                                                    Upload and Process
                                                </button>
                                            </form>
                                        </div>
                                    </div>

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

                                    <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('singleActivationForm');
        const bulkForm = document.getElementById('bulkActivationForm');
        const progressBar = document.getElementById('progressBar');
        const progressBarInner = progressBar.querySelector('.progress-bar');
        const resultArea = document.getElementById('resultArea');
        const resultTable = document.getElementById('resultTable');

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

            Swal.fire({
                title: 'Activating Member',
                text: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

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

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

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

            progressBar.style.display = 'block';
            progressBarInner.style.width = '0%';
            progressBarInner.textContent = 'Processing...';
            resultArea.style.display = 'none';
            resultTable.innerHTML = '';

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

                // Update progress bar
                const updateProgress = (current, total) => {
                    const percent = Math.round((current / total) * 100);
                    progressBarInner.style.width = `${percent}%`;
                    progressBarInner.textContent = `Processing ${current} of ${total}`;
                };

                // Process each member
                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++;
                    updateProgress(processed, total);
                });

                resultArea.style.display = 'block';

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