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

                    <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 Member Card Operations</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">Request Member Card</h5>
                                            <form id="cardRequestForm">
                                                <div class="mb-3">
                                                    <label class="form-label">Member Number</label>
                                                    <input type="text" class="form-control" name="membershipNumber" required>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Staff Number</label>
                                                    <input type="text" class="form-control" name="staffNumber">
                                                    <small class="text-muted">Optional</small>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Card Type</label>
                                                    <select class="form-select" name="cardType" required>
                                                        <option value="NEW">New Card</option>
                                                        <option value="REPRINT">Card Reprint</option>
                                                        <option value="REPLACE">Card Replacement</option>
                                                    </select>
                                                </div>

                                                <div class="mb-3" id="reprintReasonDiv" style="display:none;">
                                                    <label class="form-label">Reprint/Replacement Reason</label>
                                                    <select class="form-select" name="reprintReason">
                                                        <option value="LOST">Card Lost</option>
                                                        <option value="DAMAGED">Card Damaged</option>
                                                        <option value="EXPIRED">Card Expired</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-primary">
                                                    <i class="ri-bank-card-line align-middle me-1"></i>
                                                    Submit Card Request
                                                </button>
                                            </form>
                                        </div>

                                        <div class="col-lg-6">
                                            <h5 class="fs-15 mb-4">Bulk Card Operations</h5>
                                            <form id="bulkCardForm">
                                                <div class="mb-3">
                                                    <label class="form-label">Operation Type</label>
                                                    <select class="form-select" name="operationType" required>
                                                        <option value="">Select Operation</option>
                                                        <option value="REQUEST">Request New Cards</option>
                                                        <option value="REPRINT">Request Reprints</option>
                                                        <option value="REMOVE_FP">Remove Fingerprints</option>
                                                    </select>
                                                </div>

                                                <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 request_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>

                                                <a href="download_card_request_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" 
                                             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>Operation</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>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
    const cardRequestForm = document.getElementById('cardRequestForm');
    const bulkCardForm = document.getElementById('bulkCardForm');
    const cardTypeSelect = document.querySelector('select[name="cardType"]');
    const reprintReasonDiv = document.getElementById('reprintReasonDiv');
    const reprintReasonSelect = document.querySelector('select[name="reprintReason"]');
    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');

    // Handle card type selection
    cardTypeSelect?.addEventListener('change', function() {
        reprintReasonDiv.style.display = 
            (this.value === 'REPRINT' || this.value === 'REPLACE') ? 'block' : 'none';
        
        if (this.value === 'NEW') {
            reprintReasonSelect.value = '';
            otherReasonDiv.style.display = 'none';
        }
    });

    // Handle reprint reason selection
    reprintReasonSelect?.addEventListener('change', function() {
        otherReasonDiv.style.display = this.value === 'OTHER' ? 'block' : 'none';
        if (this.value !== 'OTHER') {
            otherReasonDiv.querySelector('textarea').value = '';
        }
    });

    // Single card request form submission
    cardRequestForm?.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(cardRequestForm);
        
        // Add country code from provider configuration
        formData.append('countryCode', '<?php echo $provider['country_code']; ?>');

        // Handle reason logic
        if (formData.get('cardType') !== 'NEW') {
            if (formData.get('reprintReason') === 'OTHER') {
                formData.set('reprintReason', formData.get('otherReason'));
            }
        }

        Swal.fire({
            title: 'Confirm Card Request',
            text: `Are you sure you want to ${formData.get('cardType').toLowerCase()} this member's card?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Continue',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Processing Request',
                    text: 'Please wait...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // Determine endpoint based on operation type
                let endpoint;
                switch(formData.get('cardType')) {
                    case 'NEW':
                        endpoint = 'request_edi_card.php';
                        break;
                    case 'REPRINT':
                        endpoint = 'reprint_edi_card.php';
                        break;
                    case 'REPLACE':
                        endpoint = 'replace_edi_card.php';
                        break;
                }

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

                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: data.message || 'Card request processed successfully'
                    }).then(() => {
                        cardRequestForm.reset();
                        reprintReasonDiv.style.display = 'none';
                        otherReasonDiv.style.display = 'none';
                    });
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message
                    });
                });
            }
        });
    });

    // Bulk card operations form submission
    bulkCardForm?.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(bulkCardForm);
        formData.append('countryCode', '<?php echo $provider['country_code']; ?>');

        const operationType = formData.get('operationType');
        if (!operationType) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Please select an operation type'
            });
            return;
        }

        Swal.fire({
            title: 'Confirm Bulk Operation',
            text: 'Are you sure you want to process these card operations?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Process',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                progressBar.style.display = 'block';
                progressBarInner.style.width = '0%';
                progressBarInner.textContent = 'Processing...';
                resultArea.style.display = 'none';
                resultTable.innerHTML = '';

                let endpoint;
                switch(operationType) {
                    case 'REQUEST':
                        endpoint = 'process_bulk_card_requests.php';
                        break;
                    case 'REPRINT':
                        endpoint = 'process_bulk_reprints.php';
                        break;
                    case 'REMOVE_FP':
                        endpoint = 'process_bulk_fingerprint_removal.php';
                        break;
                }

                fetch(endpoint, {
                    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.requests.length;
                    
                    data.requests.forEach(request => {
                        const row = document.createElement('tr');
                        const statusClass = request.success ? 'success' : 'danger';
                        row.innerHTML = `
                            <td>${request.member_number}</td>
                            <td>${request.operation}</td>
                            <td><span class="badge bg-${statusClass}">
                                ${request.success ? 'Success' : 'Failed'}
                            </span></td>
                            <td>${request.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.requests.filter(r => r.success).length;
                        Swal.fire({
                            icon: successCount === total ? 'success' : 'warning',
                            title: 'Processing Complete',
                            html: `
                                Successfully processed ${successCount} of ${total} requests<br>
                                ${successCount < total ? 'See results table for details' : ''}
                            `
                        });
                    }
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message
                    });
                })
                .finally(() => {
                    progressBar.style.display = 'none';
                });
            }
        });
    });

    // Download template button handler
    document.querySelector('a[href="download_card_request_template.php"]')?.addEventListener('click', function(e) {
        e.preventDefault();
        const operationType = document.querySelector('select[name="operationType"]').value;
        if (!operationType) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Please select an operation type first'
            });
            return;
        }
        window.location.href = `download_card_request_template.php?type=${operationType}`;
    });
});
    </script>
</body>
</html>