<?php
// Start session
session_start();

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

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

// Get admin data
$admin_id = $_SESSION['user_id'];
$admin_username = $_SESSION['username'];

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

// 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;

// Count expired items
$count_query = "
    SELECT COUNT(*) as total
    FROM color_stock_items_semarang
    WHERE (status = 'Tersedia' OR status = 'Renew' OR status = 'Expired')
    AND tanggal_kedaluwarsa < CURDATE()
";
$count_result = $conn->query($count_query);
$expired_count = 0;

if ($count_result && $row = $count_result->fetch_assoc()) {
    $expired_count = $row['total'];
}

// If performing renewal
if ($action === 'renew' && $expired_count > 0) {
    // Log start of auto-renewal process
    log_activity($conn, $admin_id, 'admin', 'Auto Renew Start', "Admin $admin_username started auto-renewal process for $expired_count items");
    
    // Get all expired items
    $expired_items_query = "
        SELECT id, color_id, component_id, kode_barang, stock_number, lokasi, qr_code,
               tanggal_pembuatan, tanggal_kedaluwarsa, keterangan, rack_no
        FROM color_stock_items_semarang
        WHERE (status = 'Tersedia' OR status = 'Renew' OR status = 'Expired')
        AND tanggal_kedaluwarsa < CURDATE()
    ";
    
    $result = $conn->query($expired_items_query);
    
    if ($result && $result->num_rows > 0) {
        $renewed_count = 0;
        $failed_count = 0;
        
        while ($item = $result->fetch_assoc()) {
            // Start transaction for each item
            $conn->begin_transaction();
            
            try {
                $stock_item_id = $item['id'];
                
                // Insert into renew_code_history_semarang
                $history_stmt = $conn->prepare("
                    INSERT INTO renew_code_history_semarang 
                    (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']
                );
                
                $history_stmt->execute();
                $history_stmt->close();
                
                // Find the next available code in the sequence
                $next_code_stmt = $conn->prepare("
                    SELECT MAX(CAST(SUBSTRING(kode_barang, 4) AS UNSIGNED)) as last_code
                    FROM color_stock_items_semarang
                    WHERE kode_barang LIKE 'CP.%'
                ");
                $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'];
                $new_code_number = $last_code + 1;
                $new_code = 'CP.' . str_pad($new_code_number, 4, '0', STR_PAD_LEFT);
                
                // 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_semarang 
                    SET kode_barang = ?, 
                        status = 'Tersedia', 
                        tanggal_pembuatan = ?, 
                        tanggal_kedaluwarsa = ? 
                    WHERE id = ?
                ");
                
                $update_stmt->bind_param("sssi", $new_code, $tanggal_pembuatan, $tanggal_kedaluwarsa, $stock_item_id);
                $update_stmt->execute();
                $update_stmt->close();
                
                // Log the admin-initiated auto-renew action
                log_activity($conn, $admin_id, 'admin', 'Auto Renew Item', "Admin auto-renewed color item ID: $stock_item_id, New code: $new_code");
                
                // Commit transaction
                $conn->commit();
                $renewed_count++;
                
                // Add to results
                $results[] = [
                    'id' => $stock_item_id,
                    'old_code' => $item['kode_barang'],
                    'new_code' => $new_code,
                    'status' => 'success'
                ];
                
            } catch (Exception $e) {
                // Rollback transaction on error
                $conn->rollback();
                $failed_count++;
                
                // Add to results
                $results[] = [
                    'id' => $stock_item_id,
                    'old_code' => $item['kode_barang'],
                    'error' => $e->getMessage(),
                    'status' => 'error'
                ];
            }
        }
        
        // Set success message
        $success = "Auto-renewal process completed. Successfully renewed $renewed_count items.";
        
        if ($failed_count > 0) {
            $error = "Failed to renew $failed_count items. See details below.";
        }
        
        // Log completion
        log_activity($conn, $admin_id, 'admin', 'Auto Renew Complete', 
            "Admin $admin_username completed auto-renewal process. Renewed: $renewed_count, Failed: $failed_count");
    } else {
        $error = "No expired items found or error retrieving item list.";
    }
}

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

<!-- Main Content Area -->
<main class="flex-1 p-2 sm:p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-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">Auto Renew Expired Items</h2>
                <p class="text-gray-600 text-sm sm:text-base">Automatically renew items that have passed their expiration date</p>
            </div>
            <div class="mt-3 sm:mt-0">
                <a href="stok_color_admin.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">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Stock Color
                </a>
            </div>
        </div>
    </div>
    
    <?php if (isset($success)): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-3 py-2 sm:px-4 sm:py-3 rounded relative mb-4 sm:mb-6" role="alert">
        <strong class="font-bold">Success!</strong>
        <span class="block sm:inline"><?php echo $success; ?></span>
    </div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-3 py-2 sm:px-4 sm:py-3 rounded relative mb-4 sm:mb-6" role="alert">
        <strong class="font-bold">Error!</strong>
        <span class="block sm:inline"><?php echo $error; ?></span>
    </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">Expired Items Detected</h3>
        
        <?php if ($expired_count > 0): ?>
        <p class="mb-4">There are <span class="font-bold text-red-600"><?php echo $expired_count; ?></span> item(s) with an expired status that require renewal.</p>
        
        <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-yellow-700">
                        <span class="font-medium">Warning:</span> This action will automatically renew all expired items, giving them new codes, a current creation date, and a new expiration date 6 months from today.
                    </p>
                </div>
            </div>
        </div>
        
        <div class="flex flex-col sm:flex-row gap-3">
            <a href="auto_renew_expired.php?action=renew" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out text-center">
                <i class="fas fa-sync-alt mr-2"></i>Proceed with Auto-Renewal
            </a>
            <a href="stok_color_admin.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">
                Cancel
            </a>
        </div>
        <?php else: ?>
        <p class="mb-4">There are no expired items that require renewal at this time.</p>
        <a href="stok_color_admin.php" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out inline-block">
            Return to 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">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Auto-Renewal Results</h3>
        
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-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">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">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>
                        <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">
                            <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-gray-100 text-gray-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">
                            <?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">
                                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">
                                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">Successfully renewed</span>
                            <?php else: ?>
                            <span class="text-red-600"><?php echo htmlspecialchars($res['error']); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <div class="mt-4">
            <a href="stok_color_admin.php" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out inline-block">
                Return to Stock Color Management
            </a>
        </div>
    </div>
    <?php endif; ?>
</main>

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