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

// Fetch EDI providers
$sql = "SELECT p.*, 
        p.edi_type, 
        u1.username as configured_by,
        u2.username as modified_by,
        (SELECT COUNT(*) FROM edi_integration_logs WHERE provider_id = p.provider_id) as log_count
        FROM edi_providers p
        LEFT JOIN users u1 ON p.created_by = u1.user_id
        LEFT JOIN users u2 ON p.modified_by = u2.user_id
        ORDER BY p.provider_name";
$result = $conn->query($sql);
$providers = $result->fetch_all(MYSQLI_ASSOC);

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'EDI Integration Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <style>
        .status-badge {
            width: 100px;
            text-align: center;
        }
        .provider-card {
            transition: all 0.3s ease;
        }
        .provider-card:hover {
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
        }
    </style>
</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' => 'System Settings', 'title' => 'EDI Integration Management')); ?>

                    <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">EDI Providers</h4>
                                </div>
                                
                                <div class="card-body">
                                    <div class="row">
                                        <?php foreach ($providers as $provider): ?>
                                        <div class="col-xl-4 col-md-6 mb-4">
                                            <div class="card h-100 provider-card border">
                                                <div class="card-body">
                                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                                        <h5 class="card-title mb-0">
                                                            <?php echo htmlspecialchars($provider['provider_name']); ?>
                                                        </h5>
                                                        <div class="form-check form-switch">
                                                            <input class="form-check-input" type="checkbox" 
                                                                   id="activeSwitch_<?php echo $provider['provider_id']; ?>"
                                                                   <?php echo $provider['is_active'] ? 'checked' : ''; ?>
                                                                   <?php echo $provider['status'] !== 'CONFIGURED' ? 'disabled' : ''; ?>
                                                                   onchange="toggleProvider(<?php echo $provider['provider_id']; ?>)">
                                                        </div>
                                                    </div>

                                                    <p class="text-muted mb-3">
                                                        <?php echo htmlspecialchars($provider['description']); ?>
                                                    </p>

                                                    <div class="mb-3">
                                                        <span class="badge bg-<?php 
                                                            echo $provider['status'] === 'CONFIGURED' ? 'success' : 
                                                                ($provider['status'] === 'ERROR' ? 'danger' : 'warning'); 
                                                            ?> status-badge">
                                                            <?php echo $provider['status']; ?>
                                                        </span>
                                                    </div>

                                                    <?php if ($provider['status'] === 'ERROR'): ?>
                                                    <div class="alert alert-danger mb-3">
                                                        <?php echo htmlspecialchars($provider['error_message']); ?>
                                                    </div>
                                                    <?php endif; ?>

                                                    <div class="table-responsive">
                                                        <table class="table table-sm table-borderless mb-0">
                                                            <tr>
                                                                <th width="140">API Status:</th>
                                                                <td>
                                                                    <span class="badge bg-<?php 
                                                                        echo $provider['api_base_url'] ? 'success' : 'danger'; 
                                                                    ?>">
                                                                        <?php echo $provider['api_base_url'] ? 'Connected' : 'Not Connected'; ?>
                                                                    </span>
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <th>Last Sync:</th>
                                                                <td>
                                                                    <?php echo $provider['last_sync'] ? 
                                                                        date('d M Y H:i', strtotime($provider['last_sync'])) : 
                                                                        'Never'; ?>
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <th>Configured By:</th>
                                                                <td><?php echo $provider['configured_by']; ?></td>
                                                            </tr>
                                                            <?php if ($provider['modified_by']): ?>
                                                            <tr>
                                                                <th>Last Modified:</th>
                                                                <td>
                                                                    <?php echo $provider['modified_by']; ?> on 
                                                                    <?php echo date('d M Y H:i', strtotime($provider['modified_at'])); ?>
                                                                </td>
                                                            </tr>
                                                            <?php endif; ?>
                                                        </table>
                                                    </div>

                                                    <div class="d-flex justify-content-between align-items-center mt-4">
                                                       <button type="button" class="btn btn-primary btn-sm" 
                                                                onclick="configureEdiSettings('<?php echo $provider['edi_type']; ?>')">
                                                            <i class="ri-settings-3-line align-middle me-1"></i>
                                                            Configure <?php echo $provider['edi_type']; ?> Integration
                                                        </button>
                                                        
                                                        <?php if ($provider['log_count'] > 0): ?>
                                                        <button type="button" class="btn btn-info btn-sm"
                                                                onclick="viewLogs(<?php echo $provider['provider_id']; ?>)">
                                                            <i class="ri-file-list-3-line align-middle me-1"></i>
                                                            View Logs (<?php echo $provider['log_count']; ?>)
                                                        </button>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </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>
        function toggleProvider(providerId) {
    const switchElement = document.getElementById(`activeSwitch_${providerId}`);
    const isActive = switchElement.checked;

    Swal.fire({
        title: `${isActive ? 'Activate' : 'Deactivate'} Provider?`,
        text: `This will ${isActive ? 'enable' : 'disable'} the EDI integration. Are you sure?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Continue',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('toggle_edi_provider.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    provider_id: providerId,
                    is_active: isActive
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: data.message
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    throw new Error(data.error || 'Failed to update provider status');
                }
            })
            .catch(error => {
                switchElement.checked = !isActive;
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
        } else {
            switchElement.checked = !isActive;
        }
    });
}

function configureEdiSettings(ediType) {
    // First fetch existing configuration for the specific EDI type without provider ID
    fetch(`get_edi_config.php?type=${encodeURIComponent(ediType)}`)
        .then(response => response.json())
        .then(data => {
            if (!data.success && !data.config) {
                // Handle case where no config exists yet - provide empty config
                data = { success: true, config: {} };
            }

            // Show configuration modal based on EDI type
            switch (ediType.toUpperCase()) {
                case 'SMART':
                    showSmartEdiConfig(data.config || {});
                    break;
                case 'SLADE':
                    showSladeEdiConfig(data.config || {});
                    break;
                case 'LCT':
                    showLctEdiConfig(data.config || {});
                    break;
                default:
                    throw new Error('Unknown EDI type');
            }
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message || 'Failed to load configuration'
            });
        });
}

function showSmartEdiConfig(config) {
    Swal.fire({
        title: 'Configure SMART EDI Integration',
        html: `
            <form id="configForm" class="text-start">
                <input type="hidden" id="ediType" value="SMART">
                
                <div class="mb-3">
                    <label class="form-label">Auth URL</label>
                    <input type="url" class="form-control" id="authUrl" 
                           value="${config.auth_url || 'https://data.smartapplicationsgroup.com/auth/integ-clients/oauth/token'}" required>
                    <small class="text-muted">SMART Authorization URL</small>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">API Base URL</label>
                    <input type="url" class="form-control" id="apiBaseUrl" 
                           value="${config.api_base_url || 'https://data.smartapplicationsgroup.com/api/v2/integqa/'}" required>
                    <small class="text-muted">SMART API Base URL</small>
                </div>

                <div class="mb-3">
                    <label class="form-label">Client ID</label>
                    <input type="text" class="form-control" id="clientId" 
                           value="${config.client_id || ''}" required>
                    <small class="text-muted">Provided by SMART</small>
                </div>

                <div class="mb-3">
                    <label class="form-label">Client Secret</label>
                    <div class="input-group">
                        <input type="password" class="form-control" id="clientSecret" 
                               value="${config.client_secret || ''}" required>
                        <button class="btn btn-outline-secondary" type="button" 
                                onclick="togglePassword('clientSecret')">
                            <i class="ri-eye-line"></i>
                        </button>
                    </div>
                    <small class="text-muted">Provided by SMART</small>
                </div>

                <div class="mb-3">
                    <label class="form-label">Customer ID</label>
                    <input type="text" class="form-control" id="customerId" 
                           value="${config.customer_id || ''}" required>
                    <small class="text-muted">Your unique customer identifier from SMART</small>
                </div>

                <div class="mb-3">
                    <label class="form-label">Country Code</label>
                    <select class="form-select" id="countryCode" required>
                        <option value="">Select Country</option>
                        <option value="KE" ${config.country_code === 'KE' ? 'selected' : ''}>Kenya</option>
                        <option value="UG" ${config.country_code === 'UG' ? 'selected' : ''}>Uganda</option>
                        <option value="TZ" ${config.country_code === 'TZ' ? 'selected' : ''}>Tanzania</option>
                        <option value="RW" ${config.country_code === 'RW' ? 'selected' : ''}>Rwanda</option>
                    </select>
                    <small class="text-muted">Country of operation</small>
                </div>

                <div class="alert alert-info">
                    <i class="ri-information-line me-2"></i>
                    The token will be automatically managed and refreshed every 2 hours.
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: 'Save Configuration',
        cancelButtonText: 'Cancel',
        width: '600px',
        preConfirm: () => {
            return {
                type: 'SMART',
                auth_url: document.getElementById('authUrl').value,
                api_base_url: document.getElementById('apiBaseUrl').value,
                client_id: document.getElementById('clientId').value,
                client_secret: document.getElementById('clientSecret').value,
                customer_id: document.getElementById('customerId').value,
                country_code: document.getElementById('countryCode').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            saveEdiConfig(result.value);
        }
    });
}

function showSladeEdiConfig(config) {
    Swal.fire({
        title: 'Configure SLADE EDI Integration',
        html: `
            <form id="configForm" class="text-start">
                <input type="hidden" id="ediType" value="SLADE">
                <!-- Add SLADE-specific configuration fields here when documentation is available -->
                <div class="alert alert-info">
                    SLADE EDI configuration options will be available soon.
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: 'Save Configuration',
        cancelButtonText: 'Cancel',
        width: '600px'
    });
}

function showLctEdiConfig(config) {
    Swal.fire({
        title: 'Configure LCT EDI Integration',
        html: `
            <form id="configForm" class="text-start">
                <input type="hidden" id="ediType" value="LCT">
                <!-- Add LCT-specific configuration fields here when documentation is available -->
                <div class="alert alert-info">
                    LCT EDI configuration options will be available soon.
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: 'Save Configuration',
        cancelButtonText: 'Cancel',
        width: '600px'
    });
}

function saveEdiConfig(config) {
    fetch('save_edi_config.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(config)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: `${config.type} EDI configuration saved successfully`
            }).then(() => {
                testEdiConnection(config.type);
            });
        } else {
            throw new Error(data.error || 'Failed to save configuration');
        }
    })
    .catch(error => {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: error.message
        });
    });
}

function testEdiConnection(ediType) {
    Swal.fire({
        title: `Testing ${ediType} EDI Connection`,
        text: 'Please wait while we test the connection...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch(`test_edi_connection.php?type=${ediType}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Connection Successful',
                    html: `
                        <div class="text-start">
                            <p><strong>Authentication:</strong> Successful</p>
                            <p><strong>Token Type:</strong> ${data.token_type}</p>
                            <p><strong>Token Expires:</strong> ${data.expires_in} seconds</p>
                            <p class="mb-0"><small class="text-muted">The token will be automatically refreshed before expiration.</small></p>
                        </div>
                    `
                }).then(() => {
                    location.reload();
                });
            } else {
                throw new Error(data.error || 'Connection test failed');
            }
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Connection Failed',
                text: error.message
            });
        });
}

function togglePassword(elementId) {
    const input = document.getElementById(elementId);
    input.type = input.type === 'password' ? 'text' : 'password';
}

function viewLogs(providerId) {
    fetch(`get_edi_logs.php?provider_id=${providerId}`)
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || 'Failed to fetch logs');
            }

            let logsHtml = '<div class="table-responsive"><table class="table table-bordered">';
            logsHtml += `
                <thead>
                    <tr>
                        <th>Date/Time</th>
                        <th>Event</th>
                        <th>Status</th>
                        <th>Message</th>
                    </tr>
                </thead>
                <tbody>
            `;

            data.logs.forEach(log => {
                const statusClass = log.status === 'SUCCESS' ? 'success' : 
                                  (log.status === 'WARNING' ? 'warning' : 'danger');
                logsHtml += `
                    <tr>
                        <td>${log.created_at}</td>
                        <td>${log.event_type}</td>
                        <td><span class="badge bg-${statusClass}">${log.status}</span></td>
                        <td>${log.message}</td>
                    </tr>
                `;
            });

            logsHtml += '</tbody></table></div>';

            Swal.fire({
                title: 'Integration Logs',
                html: logsHtml,
                width: '800px',
                confirmButtonText: 'Close'
            });
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message
            });
        });
}
    </script>
</body>
</html>