<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not IT
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT data
$it_id = $_SESSION['user_id'];
$it_username = $_SESSION['username'];

// Set page title
$page_title = "Auto Renew Expired Items - IT Support";

// Check if confirmation is requested or renewal is to be performed
$action = isset($_GET['action']) ? $_GET['action'] : 'confirm';

// Variable to store results, errors, and success messages
$results = [];
$error = null;
$success = null;
$summary_stats = [
    'total_processed' => 0,
    'successful' => 0,
    'failed' => 0,
    'by_buyer' => [],
    'by_status' => []
];

// Enhanced query to get expired items with more details
$count_query = "
    SELECT 
        COUNT(*) as total,
        GROUP_CONCAT(DISTINCT b.nama_buyer) as buyers_affected,
        MIN(csi.tanggal_kedaluwarsa) as oldest_expiry,
        MAX(csi.tanggal_kedaluwarsa) as newest_expiry
    FROM color_stock_items csi
    JOIN master_color_panel mcp ON csi.color_id = mcp.id
    JOIN buyers b ON mcp.buyer_id = b.id
    WHERE csi.status IN ('Tersedia', 'Renew', 'Expired')
    AND csi.tanggal_kedaluwarsa < CURDATE()
";

$count_result = $conn->query($count_query);
$expired_info = $count_result->fetch_assoc();
$expired_count = $expired_info['total'] ?? 0;

// If performing renewal
if ($action === 'renew' && $expired_count > 0) {
    // Log start of auto-renewal process
    log_activity($conn, $it_id, 'it', 'Auto Renew Start', "IT user $it_username started auto-renewal process for $expired_count items");
    
    // Get all expired items with detailed information
    $expired_items_query = "
        SELECT 
            csi.id, csi.color_id, csi.component_id, csi.kode_barang, 
            csi.stock_number, csi.lokasi, csi.qr_code,
            csi.tanggal_pembuatan, csi.tanggal_kedaluwarsa, 
            csi.keterangan, csi.rack_no, csi.status,
            mcp.code_color, b.nama_buyer, cc.component_name
        FROM color_stock_items csi
        JOIN master_color_panel mcp ON csi.color_id = mcp.id
        JOIN buyers b ON mcp.buyer_id = b.id
        JOIN color_components cc ON csi.component_id = cc.id
        WHERE csi.status IN ('Tersedia', 'Renew', 'Expired')
        AND csi.tanggal_kedaluwarsa < CURDATE()
        ORDER BY csi.tanggal_kedaluwarsa ASC, b.nama_buyer, mcp.code_color
    ";
    
    $result = $conn->query($expired_items_query);
    
    if ($result && $result->num_rows > 0) {
        $renewed_count = 0;
        $failed_count = 0;
        $batch_size = 50; // Process in batches
        $batch_count = 0;
        
        while ($item = $result->fetch_assoc()) {
            // Start transaction for each item
            $conn->begin_transaction();
            
            try {
                $stock_item_id = $item['id'];
                $batch_count++;
                
                // Validate item is still eligible for renewal
                $check_stmt = $conn->prepare("
                    SELECT status FROM color_stock_items 
                    WHERE id = ? AND status IN ('Tersedia', 'Renew', 'Expired')
                ");
                $check_stmt->bind_param("i", $stock_item_id);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                
                if ($check_result->num_rows == 0) {
                    throw new Exception("Item tidak lagi eligible untuk renewal");
                }
                $check_stmt->close();
                
                // Insert into renew_code_history
                $history_stmt = $conn->prepare("
                    INSERT INTO renew_code_history 
                    (original_id, color_id, component_id, kode_barang, stock_number, lokasi, qr_code, 
                    tanggal_pembuatan, tanggal_kedaluwarsa, keterangan, renewed_date) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                ");
                
                $history_stmt->bind_param(
                    "iiisisssss", 
                    $stock_item_id, 
                    $item['color_id'], 
                    $item['component_id'], 
                    $item['kode_barang'], 
                    $item['stock_number'], 
                    $item['lokasi'], 
                    $item['qr_code'], 
                    $item['tanggal_pembuatan'], 
                    $item['tanggal_kedaluwarsa'], 
                    $item['keterangan']
                );
                
                if (!$history_stmt->execute()) {
                    throw new Exception("Gagal menyimpan history: " . $history_stmt->error);
                }
                $history_stmt->close();
                
                // Find the next available code with better error handling
                $next_code_stmt = $conn->prepare("
                    SELECT MAX(CAST(SUBSTRING(kode_barang, 4) AS UNSIGNED)) as last_code
                    FROM color_stock_items
                    WHERE kode_barang LIKE 'CP.%'
                    AND kode_barang REGEXP '^CP\\.[0-9]+$'
                ");
                $next_code_stmt->execute();
                $next_code_result = $next_code_stmt->get_result()->fetch_assoc();
                $next_code_stmt->close();
                
                $last_code = $next_code_result['last_code'] ?? 0;
                $new_code_number = $last_code + 1;
                
                // Ensure unique code
                do {
                    $new_code = 'CP.' . str_pad($new_code_number, 4, '0', STR_PAD_LEFT);
                    $check_code = $conn->prepare("SELECT id FROM color_stock_items WHERE kode_barang = ?");
                    $check_code->bind_param("s", $new_code);
                    $check_code->execute();
                    if ($check_code->get_result()->num_rows > 0) {
                        $new_code_number++;
                    } else {
                        break;
                    }
                    $check_code->close();
                } while (true);
                
                // Set new dates
                $today_date = new DateTime();
                $tanggal_pembuatan = $today_date->format('Y-m-d');
                
                $expiry_date = clone $today_date;
                $expiry_date->add(new DateInterval('P6M')); // Add 6 months
                $tanggal_kedaluwarsa = $expiry_date->format('Y-m-d');
                
                // Update the current item with new information
                $update_stmt = $conn->prepare("
                    UPDATE color_stock_items 
                    SET kode_barang = ?, 
                        status = 'Tersedia', 
                        tanggal_pembuatan = ?, 
                        tanggal_kedaluwarsa = ?,
                        qr_code = NULL
                    WHERE id = ?
                ");
                
                $update_stmt->bind_param("sssi", $new_code, $tanggal_pembuatan, $tanggal_kedaluwarsa, $stock_item_id);
                
                if (!$update_stmt->execute()) {
                    throw new Exception("Gagal update item: " . $update_stmt->error);
                }
                $update_stmt->close();
                
                // Log the IT-initiated auto-renew action
                log_activity($conn, $it_id, 'it', 'Auto Renew Item', 
                    "IT auto-renewed: {$item['nama_buyer']} - {$item['code_color']} - {$item['component_name']} (ID: $stock_item_id, New: $new_code)");
                
                // Commit transaction
                $conn->commit();
                $renewed_count++;
                
                // Update statistics
                if (!isset($summary_stats['by_buyer'][$item['nama_buyer']])) {
                    $summary_stats['by_buyer'][$item['nama_buyer']] = ['success' => 0, 'failed' => 0];
                }
                $summary_stats['by_buyer'][$item['nama_buyer']]['success']++;
                
                // Add to results
                $results[] = [
                    'id' => $stock_item_id,
                    'old_code' => $item['kode_barang'],
                    'new_code' => $new_code,
                    'buyer' => $item['nama_buyer'],
                    'color' => $item['code_color'],
                    'component' => $item['component_name'],
                    'old_expiry' => $item['tanggal_kedaluwarsa'],
                    'new_expiry' => $tanggal_kedaluwarsa,
                    'status' => 'success'
                ];
                
                // Process in batches to prevent timeout
                if ($batch_count % $batch_size == 0) {
                    sleep(1); // Brief pause between batches
                }
                
            } catch (Exception $e) {
                // Rollback transaction on error
                $conn->rollback();
                $failed_count++;
                
                // Update statistics
                if (!isset($summary_stats['by_buyer'][$item['nama_buyer']])) {
                    $summary_stats['by_buyer'][$item['nama_buyer']] = ['success' => 0, 'failed' => 0];
                }
                $summary_stats['by_buyer'][$item['nama_buyer']]['failed']++;
                
                // Add to results
                $results[] = [
                    'id' => $stock_item_id,
                    'old_code' => $item['kode_barang'],
                    'buyer' => $item['nama_buyer'],
                    'color' => $item['code_color'],
                    'component' => $item['component_name'],
                    'error' => $e->getMessage(),
                    'status' => 'error'
                ];
                
                // Log error
                error_log("Auto-renew error for item $stock_item_id: " . $e->getMessage());
            }
        }
        
        // Update summary statistics
        $summary_stats['total_processed'] = $renewed_count + $failed_count;
        $summary_stats['successful'] = $renewed_count;
        $summary_stats['failed'] = $failed_count;
        
        // Set success message
        $success = "Proses auto-renewal selesai. Berhasil memperbarui $renewed_count item dari total " . $summary_stats['total_processed'] . " item.";
        
        if ($failed_count > 0) {
            $error = "Gagal memperbarui $failed_count item. Lihat detail di bawah.";
        }
        
        // Log completion
        log_activity($conn, $it_id, 'it', 'Auto Renew Complete', 
            "IT user $it_username completed auto-renewal. Success: $renewed_count, Failed: $failed_count");
    } else {
        $error = "Tidak ada item kadaluarsa yang ditemukan atau error saat mengambil data.";
    }
}

// Include header
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-2 sm:p-6 overflow-auto bg-gradient-to-br from-purple-100 via-blue-100 to-indigo-100">
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6 mb-4 sm:mb-6">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center">
            <div>
                <h2 class="text-xl sm:text-2xl font-bold text-gray-800 mb-2 sm:mb-4">
                    <i class="fas fa-laptop-code text-purple-600 mr-2"></i>
                    Auto Renew Expired Items - IT Support
                </h2>
                <p class="text-gray-600 text-sm sm:text-base">Otomatis perbarui item yang telah melewati tanggal kadaluarsa</p>
            </div>
            <div class="mt-3 sm:mt-0">
                <a href="stok_color_it.php" class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 text-sm sm:text-base rounded-md transition duration-150 ease-in-out inline-block shadow-md hover:shadow-lg">
                    <i class="fas fa-arrow-left mr-2"></i>Kembali ke Stock Color
                </a>
            </div>
        </div>
    </div>
    
    <?php if (isset($success)): ?>
    <div class="bg-green-100 border-l-4 border-green-400 text-green-700 px-3 py-2 sm:px-4 sm:py-3 rounded-lg relative mb-4 sm:mb-6 shadow-md" role="alert">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-check-circle text-green-400"></i>
            </div>
            <div class="ml-3">
                <strong class="font-bold">Success!</strong>
                <span class="block sm:inline"><?php echo $success; ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
    <div class="bg-red-100 border-l-4 border-red-400 text-red-700 px-3 py-2 sm:px-4 sm:py-3 rounded-lg relative mb-4 sm:mb-6 shadow-md" role="alert">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-times-circle text-red-400"></i>
            </div>
            <div class="ml-3">
                <strong class="font-bold">Error!</strong>
                <span class="block sm:inline"><?php echo $error; ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Confirmation Section -->
    <?php if ($action === 'confirm'): ?>
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6 mb-4 sm:mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-exclamation-triangle text-yellow-500 mr-2"></i>
            Item Kadaluarsa Terdeteksi
        </h3>
        
        <?php if ($expired_count > 0): ?>
        <div class="mb-4 p-4 bg-purple-50 rounded-lg">
            <p class="mb-2">Terdapat <span class="font-bold text-purple-600 text-xl"><?php echo $expired_count; ?></span> item dengan status kadaluarsa yang perlu diperbaharui.</p>
            
            <?php if ($expired_info['buyers_affected']): ?>
            <div class="mt-3 text-sm text-gray-600">
                <p><strong>Buyer yang terpengaruh:</strong> <?php echo htmlspecialchars($expired_info['buyers_affected']); ?></p>
                <p><strong>Rentang kadaluarsa:</strong> 
                    <?php echo date('d M Y', strtotime($expired_info['oldest_expiry'])); ?> - 
                    <?php echo date('d M Y', strtotime($expired_info['newest_expiry'])); ?>
                </p>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-4 rounded-lg">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-info-circle text-yellow-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-yellow-700">
                        <span class="font-medium">Perhatian:</span> Aksi ini akan otomatis memperbarui semua item kadaluarsa dengan:
                    </p>
                    <ul class="list-disc list-inside text-sm text-yellow-700 mt-2">
                        <li>Kode barang baru (format: CP.XXXX)</li>
                        <li>Tanggal pembuatan: Hari ini</li>
                        <li>Tanggal kadaluarsa: 6 bulan dari hari ini</li>
                        <li>Status: Tersedia</li>
                        <li>QR Code akan direset (perlu generate ulang)</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <div class="bg-blue-50 border-l-4 border-blue-400 p-4 mb-4 rounded-lg">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-clock text-blue-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-blue-700">
                        <span class="font-medium">Estimasi waktu proses:</span> 
                        <?php 
                        $estimated_time = ceil($expired_count / 50); // 50 items per batch
                        echo $estimated_time . " - " . ($estimated_time + 1) . " menit";
                        ?>
                    </p>
                </div>
            </div>
        </div>
        
        <div class="flex flex-col sm:flex-row gap-3">
            <button onclick="confirmRenewal()" class="bg-purple-500 hover:bg-purple-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out text-center shadow-md hover:shadow-lg">
                <i class="fas fa-sync-alt mr-2"></i>Lanjutkan Auto-Renewal
            </button>
            <a href="stok_color_it.php" class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out text-center shadow-md hover:shadow-lg">
                Batal
            </a>
        </div>
        
        <!-- Confirmation Modal -->
        <div id="confirmModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
            <div class="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
                <h4 class="text-lg font-semibold text-gray-800 mb-4">
                    <i class="fas fa-question-circle text-purple-600 mr-2"></i>
                    Konfirmasi Auto-Renewal
                </h4>
                <p class="text-gray-600 mb-6">
                    Apakah Anda yakin ingin memperbarui <strong><?php echo $expired_count; ?> item</strong> kadaluarsa?
                    Proses ini tidak dapat dibatalkan.
                </p>
                <div class="flex justify-end gap-3">
                    <button onclick="closeConfirmModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400 transition">
                        Batal
                    </button>
                    <a href="auto_renew_expired_it.php?action=renew" class="px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600 transition">
                        <i class="fas fa-check mr-2"></i>Ya, Lanjutkan
                    </a>
                </div>
            </div>
        </div>
        
        <?php else: ?>
        <p class="mb-4">Tidak ada item kadaluarsa yang perlu diperbaharui saat ini.</p>
        <a href="stok_color_it.php" class="bg-purple-500 hover:bg-purple-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out inline-block shadow-md hover:shadow-lg">
            Kembali ke Stock Color Management
        </a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <!-- Results Section -->
    <?php if ($action === 'renew' && !empty($results)): ?>
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6 mb-4">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-list-check text-purple-600 mr-2"></i>
            Hasil Auto-Renewal
        </h3>
        
        <!-- Summary Statistics -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div class="bg-blue-50 rounded-lg p-4 border-l-4 border-blue-500">
                <div class="flex items-center">
                    <i class="fas fa-tasks text-blue-500 text-2xl mr-3"></i>
                    <div>
                        <p class="text-sm text-gray-600">Total Diproses</p>
                        <p class="text-2xl font-bold text-blue-600"><?php echo $summary_stats['total_processed']; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-green-50 rounded-lg p-4 border-l-4 border-green-500">
                <div class="flex items-center">
                    <i class="fas fa-check-circle text-green-500 text-2xl mr-3"></i>
                    <div>
                        <p class="text-sm text-gray-600">Berhasil</p>
                        <p class="text-2xl font-bold text-green-600"><?php echo $summary_stats['successful']; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-red-50 rounded-lg p-4 border-l-4 border-red-500">
                <div class="flex items-center">
                    <i class="fas fa-times-circle text-red-500 text-2xl mr-3"></i>
                    <div>
                        <p class="text-sm text-gray-600">Gagal</p>
                        <p class="text-2xl font-bold text-red-600"><?php echo $summary_stats['failed']; ?></p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Summary by Buyer -->
        <?php if (!empty($summary_stats['by_buyer'])): ?>
        <div class="mb-6">
            <h4 class="text-md font-semibold text-gray-700 mb-3">Ringkasan per Buyer</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                <?php foreach ($summary_stats['by_buyer'] as $buyer => $stats): ?>
                <div class="bg-gray-50 rounded-lg p-3 border border-gray-200">
                    <p class="font-medium text-gray-800"><?php echo htmlspecialchars($buyer); ?></p>
                    <div class="flex justify-between mt-1 text-sm">
                        <span class="text-green-600">✓ <?php echo $stats['success']; ?> berhasil</span>
                        <?php if ($stats['failed'] > 0): ?>
                        <span class="text-red-600">✗ <?php echo $stats['failed']; ?> gagal</span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Detailed Results Table -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-purple-50">
                    <tr>
                        <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer</th>
                        <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color/Component</th>
                        <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Old Code</th>
                        <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">New Code</th>
                        <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">New Expiry</th>
                        <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Details</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($results as $res): ?>
                    <tr class="hover:bg-gray-50 transition-colors duration-150">
                        <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                            <?php echo $res['id']; ?>
                        </td>
                        <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                            <?php echo htmlspecialchars($res['buyer']); ?>
                        </td>
                        <td class="px-3 py-3 text-sm text-gray-500">
                            <div><?php echo htmlspecialchars($res['color']); ?></div>
                            <div class="text-xs text-gray-400"><?php echo htmlspecialchars($res['component']); ?></div>
                        </td>
                        <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                            <span class="bg-gray-100 text-gray-800 px-2 py-1 rounded-md font-mono text-xs">
                                <?php echo $res['old_code']; ?>
                            </span>
                        </td>
                        <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                            <?php if ($res['status'] === 'success'): ?>
                            <span class="bg-purple-100 text-purple-800 px-2 py-1 rounded-md font-mono text-xs">
                                <?php echo $res['new_code']; ?>
                            </span>
                            <?php else: ?>
                            <span class="text-red-500">-</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                            <?php if ($res['status'] === 'success'): ?>
                                <?php echo date('d M Y', strtotime($res['new_expiry'])); ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td class="px-3 py-3 whitespace-nowrap">
                            <?php if ($res['status'] === 'success'): ?>
                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                <i class="fas fa-check mr-1"></i>Success
                            </span>
                            <?php else: ?>
                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                <i class="fas fa-times mr-1"></i>Failed
                            </span>
                            <?php endif; ?>
                        </td>
                        <td class="px-3 py-3 text-sm text-gray-500">
                            <?php if ($res['status'] === 'success'): ?>
                            <span class="text-green-600">Berhasil diperbaharui</span>
                            <?php else: ?>
                            <span class="text-red-600 text-xs"><?php echo htmlspecialchars($res['error']); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <div class="mt-6 flex gap-3">
            <a href="stok_color_it.php" class="bg-purple-500 hover:bg-purple-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out inline-block shadow-md hover:shadow-lg">
                <i class="fas fa-arrow-left mr-2"></i>Kembali ke Stock Color Management
            </a>
            <?php if ($summary_stats['successful'] > 0): ?>
            <button onclick="downloadReport()" class="bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out shadow-md hover:shadow-lg">
                <i class="fas fa-download mr-2"></i>Download Report
            </button>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</main>

<script>
function confirmRenewal() {
    document.getElementById('confirmModal').classList.remove('hidden');
}

function closeConfirmModal() {
    document.getElementById('confirmModal').classList.add('hidden');
}

function downloadReport() {
    // Create CSV content
    let csvContent = "data:text/csv;charset=utf-8,";
    csvContent += "ID,Buyer,Color,Component,Old Code,New Code,New Expiry,Status\n";
    
    <?php foreach ($results as $res): ?>
    csvContent += "<?php echo $res['id']; ?>,";
    csvContent += "<?php echo addslashes($res['buyer']); ?>,";
    csvContent += "<?php echo addslashes($res['color']); ?>,";
    csvContent += "<?php echo addslashes($res['component']); ?>,";
    csvContent += "<?php echo $res['old_code']; ?>,";
    csvContent += "<?php echo $res['status'] === 'success' ? $res['new_code'] : 'FAILED'; ?>,";
    csvContent += "<?php echo $res['status'] === 'success' ? date('Y-m-d', strtotime($res['new_expiry'])) : 'FAILED'; ?>,";
    csvContent += "<?php echo $res['status']; ?>\n";
    <?php endforeach; ?>
    
    // Create download link
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "auto_renewal_report_<?php echo date('Y-m-d_H-i-s'); ?>.csv");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Add loading indicator when processing
<?php if ($action === 'renew' && $expired_count > 0 && empty($results)): ?>
window.onload = function() {
    // Show loading message if somehow the page is still processing
    const main = document.querySelector('main');
    main.innerHTML = `
        <div class="flex items-center justify-center h-screen">
            <div class="text-center">
                <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-purple-500"></div>
                <p class="mt-4 text-gray-600">Processing renewal... Please wait...</p>
            </div>
        </div>
    `;
};
<?php endif; ?>
</script>

<?php include '../template_it/footer.php'; ?>