<?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 configured Smart EDI provider
$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();

if (!$provider) {
    header('Location: edi_management.php');
    exit();
}
?>

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

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Smart EDI Claims Fetch</h4>
                                </div>
                                <div class="card-body">
                                    <form id="fetchForm">
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Batch Size</label>
                                                    <input type="number" class="form-control" name="limit" 
                                                           value="100" min="1" max="1000">
                                                    <small class="text-muted">Maximum claims to fetch per request (1-1000)</small>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Auto Update Status</label>
                                                    <select class="form-select" name="isUpdate">
                                                        <option value="true">Yes - Mark as Fetched</option>
                                                        <option value="false">No - Manual Update</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-12">
                                                <button type="submit" class="btn btn-primary" id="fetchBtn">
                                                    <i class="ri-download-cloud-2-line align-middle me-1"></i>
                                                    Fetch Claims
                                                </button>
                                            </div>
                                        </div>
                                    </form>

                                    <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">
                                        <div class="table-responsive">
                                            <table class="table table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Status</th>
                                                        <th>Count</th>
                                                        <th>Last Update</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    $sql = "SELECT status, COUNT(*) as count, 
                                                           MAX(created_at) as last_update
                                                           FROM edi_claims 
                                                           WHERE provider_id = ?
                                                           GROUP BY status";
                                                    $stmt = $conn->prepare($sql);
                                                    $stmt->bind_param('i', $provider['provider_id']);
                                                    $stmt->execute();
                                                    $result = $stmt->get_result();
                                                    while ($row = $result->fetch_assoc()):
                                                        $statusClass = $row['status'] === 'PROCESSED' ? 'success' : 
                                                                    ($row['status'] === 'FAILED' ? 'danger' : 'warning');
                                                    ?>
                                                    <tr>
                                                        <td>
                                                            <span class="badge bg-<?php echo $statusClass; ?>">
                                                                <?php echo $row['status']; ?>
                                                            </span>
                                                        </td>
                                                        <td><?php echo $row['count']; ?></td>
                                                        <td>
                                                            <?php 
                                                            echo $row['last_update'] ? 
                                                                date('d M Y H:i', strtotime($row['last_update'])) : 
                                                                '-'; 
                                                            ?>
                                                        </td>
                                                    </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </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>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('fetchForm');
        const fetchBtn = document.getElementById('fetchBtn');
        const progressBar = document.getElementById('progressBar');
        const progressBarInner = progressBar.querySelector('.progress-bar');

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(form);
            fetchBtn.disabled = true;
            progressBar.style.display = 'block';
            progressBarInner.style.width = '0%';
            progressBarInner.textContent = 'Starting...';

            fetch('fetch_edi_claims.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network error');
                }
                return response.json();
            })
            .then(data => {
                if (!data.success) {
                    throw new Error(data.error || 'Failed to fetch claims');
                }

                // Update progress bar
                let progress = 0;
                const interval = setInterval(() => {
                    progress += 5;
                    progressBarInner.style.width = `${progress}%`;
                    progressBarInner.textContent = `Processing (${progress}%)`;
                    
                    if (progress >= 100) {
                        clearInterval(interval);
                        progressBarInner.textContent = 'Complete!';
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Claims Fetched Successfully',
                            html: `
                                <div class="text-start">
                                    <p><strong>Total Claims:</strong> ${data.total_claims}</p>
                                    <p><strong>New Claims:</strong> ${data.new_claims}</p>
                                    <p><strong>Updated Claims:</strong> ${data.updated_claims}</p>
                                    <p class="mb-0"><small class="text-muted">Processing completed in ${data.time_taken} seconds</small></p>
                                </div>
                            `
                        }).then(() => {
                            window.location.reload();
                        });
                    }
                }, 100);
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            })
            .finally(() => {
                fetchBtn.disabled = false;
            });
        });
    });
    </script>
</body>
</html>