<?php
// Start session
session_start();

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

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

// Get IT data
$it_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM it_users_semarang WHERE id = ?");
$stmt->bind_param("i", $it_id);
$stmt->execute();
$it_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Check for items approaching expiration or expired
function check_expiring_items() {
    global $conn;
    $today = date('Y-m-d');
    
    // Update approaching expiry (10 days before) to "Renew" status
    $conn->query("
        UPDATE color_stock_items_semarang 
        SET status = 'Renew' 
        WHERE status = 'Tersedia'
        AND tanggal_kedaluwarsa BETWEEN '$today' AND DATE_ADD('$today', INTERVAL 10 DAY)
    ");
    
    // Check for expired items
    $expired_result = $conn->query("
        SELECT COUNT(*) as count FROM color_stock_items_semarang
        WHERE (status = 'Tersedia' OR status = 'Renew')
        AND tanggal_kedaluwarsa < '$today'
    ");
    $expired = $expired_result->fetch_assoc()['count'];
    
    if ($expired > 0) {
        // Create a notice for IT
        return "Ada $expired item yang sudah kadaluarsa dan perlu diperbaharui. <a href='auto_renew_expired_it.php' class='text-purple-600 hover:underline font-medium'>Klik di sini untuk auto-renew semua</a>";
    }
    return "";
}

// Log activity
log_activity($conn, $it_id, 'it', 'Stock Color Access', 'IT user accessed stock color data page');

// Process renew action if submitted
if (isset($_POST['renew_item'])) {
    $stock_item_id = intval($_POST['stock_item_id']);
    
    // Update status to 'Renew'
    $update_stmt = $conn->prepare("UPDATE color_stock_items_semarang SET status = 'Renew' WHERE id = ?");
    $update_stmt->bind_param("i", $stock_item_id);
    
    if ($update_stmt->execute()) {
        $success_message = "Status berhasil diubah menjadi Renew. Silakan lakukan proses renew selanjutnya.";
    } else {
        $error_message = "Gagal mengubah status: " . $conn->error;
    }
    $update_stmt->close();
}

// Process execute renew action if submitted
if (isset($_POST['execute_renew'])) {
    $stock_item_id = intval($_POST['stock_item_id']);
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        // Get the current stock item data
        $current_item_stmt = $conn->prepare("
            SELECT csi.*, mcp.lemari 
            FROM color_stock_items_semarang csi
            JOIN master_color_panel_semarang mcp ON csi.color_id = mcp.id
            WHERE csi.id = ?
        ");
        $current_item_stmt->bind_param("i", $stock_item_id);
        $current_item_stmt->execute();
        $current_item = $current_item_stmt->get_result()->fetch_assoc();
        $current_item_stmt->close();
        
        if (!$current_item) {
            throw new Exception("Item tidak ditemukan.");
        }
        
        // 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, 
            $current_item['color_id'], 
            $current_item['component_id'], 
            $current_item['kode_barang'], 
            $current_item['stock_number'], 
            $current_item['lokasi'], 
            $current_item['qr_code'], 
            $current_item['tanggal_pembuatan'], 
            $current_item['tanggal_kedaluwarsa'], 
            $current_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 = new DateTime();
        $tanggal_pembuatan = $today->format('Y-m-d');
        
        $expiry_date = clone $today;
        $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 renew action
        log_activity($conn, $it_id, 'it', 'Renew Color Item', "IT user renewed color item ID: $stock_item_id, New code: $new_code");
        
        // Commit transaction
        $conn->commit();
        $success_message = "Proses renew berhasil. Kode barang baru: $new_code";
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        $error_message = "Gagal melakukan proses renew: " . $e->getMessage();
    }
}

// Get all buyers_semarang for filter
$buyer_query = "SELECT id, nama_buyer FROM buyers_semarang ORDER BY nama_buyer";
$buyer_result = $conn->query($buyer_query);

// Set page title
$page_title = "Stock Color Management - IT";

// Check for expiring/expired items
$expiry_notice = check_expiring_items();

// 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>
                    Stock Color Management - IT Support
                </h2>
                <p class="text-gray-600 text-sm sm:text-base">Kelola stock item warna dan proses pembaharuan</p>
            </div>
            <div class="mt-3 sm:mt-0 flex gap-2">
                <button type="button" onclick="viewAllRenewHistory()" class="bg-purple-500 hover:bg-purple-600 text-white font-medium py-2 px-4 text-sm sm:text-base rounded-md transition duration-150 ease-in-out shadow-md hover:shadow-lg">
                    <i class="fas fa-history mr-2"></i>History
                </button>
                <a href="dashboard_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 shadow-md hover:shadow-lg">
                    <i class="fas fa-arrow-left mr-2"></i>Kembali
                </a>
            </div>
        </div>
    </div>
    
    <?php if (!empty($expiry_notice)): ?>
    <div class="bg-yellow-100 border-l-4 border-yellow-400 text-yellow-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-exclamation-triangle text-yellow-400"></i>
            </div>
            <div class="ml-3">
                <span class="block sm:inline"><?php echo $expiry_notice; ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (isset($success_message)): ?>
    <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_message; ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (isset($error_message)): ?>
    <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_message; ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Filters Section -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6 mb-4 sm:mb-6">
        <h3 class="text-base sm:text-lg font-semibold text-gray-700 mb-3 sm:mb-4">
            <i class="fas fa-filter text-purple-600 mr-2"></i>Filter Data
        </h3>
        
        <form id="filter_form" method="get" action="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4">
                <!-- Buyer Filter -->
                <div>
                    <label for="buyer_filter" class="block text-sm font-medium text-gray-700 mb-1">Buyer</label>
                    <select id="buyer_filter" name="buyer_id" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-500">
                        <option value="">Semua Buyer</option>
                        <?php while ($buyer = $buyer_result->fetch_assoc()): ?>
                            <option value="<?php echo $buyer['id']; ?>" <?php echo (isset($_GET['buyer_id']) && $_GET['buyer_id'] == $buyer['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($buyer['nama_buyer']); ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <!-- Status Filter -->
                <div>
                    <label for="status_filter" class="block text-sm font-medium text-gray-700 mb-1">Status Item</label>
                    <select id="status_filter" name="status" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-500">
                        <option value="">Semua Status</option>
                        <option value="Tersedia" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Tersedia') ? 'selected' : ''; ?>>Tersedia</option>
                        <option value="Dipinjam" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Dipinjam') ? 'selected' : ''; ?>>Dipinjam</option>
                        <option value="Rusak" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Rusak') ? 'selected' : ''; ?>>Rusak</option>
                        <option value="Expired" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Expired') ? 'selected' : ''; ?>>Expired</option>
                        <option value="Renew" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Renew') ? 'selected' : ''; ?>>Renew</option>
                    </select>
                </div>
            </div>
            
            <!-- Apply Filters Button -->
            <div class="mt-3 sm:mt-4 flex gap-2">
                <button type="submit" class="bg-purple-500 hover:bg-purple-600 text-white font-medium py-2 px-4 text-sm rounded-md transition duration-150 ease-in-out w-full sm:w-auto shadow-md hover:shadow-lg">
                    <i class="fas fa-filter mr-2"></i>Terapkan Filter
                </button>
                <button type="button" onclick="clearFilters()" class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 text-sm rounded-md transition duration-150 ease-in-out w-full sm:w-auto shadow-md hover:shadow-lg">
                    <i class="fas fa-eraser mr-2"></i>Clear
                </button>
            </div>
        </form>
    </div>
    
    <!-- Stock Color Data -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6">
        <h3 class="text-lg sm:text-xl font-semibold text-gray-800 mb-3 sm:mb-4">
            <i class="fas fa-palette text-purple-600 mr-2"></i>Stock Color Data
        </h3>
        
        <?php
        // Build query based on filters
        $where_clauses = [];
        $params = [];
        $param_types = "";
        
        $query = "
            SELECT 
                csi.id AS stock_id,
                csi.kode_barang,
                csi.status,
                csi.tanggal_pembuatan,
                csi.tanggal_kedaluwarsa,
                csi.rack_no,
                csi.lokasi,
                csi.keterangan,
                mcp.id AS color_id,
                mcp.buyer_id,
                mcp.code_color,
                mcp.deskripsi AS color_description,
                mcp.kode_warna_hex,
                cc.id AS component_id,
                cc.component_name,
                b.nama_buyer,
                b.kode_buyer
            FROM 
                color_stock_items_semarang csi
            JOIN 
                master_color_panel_semarang mcp ON csi.color_id = mcp.id
            JOIN 
                color_components_semarang cc ON csi.component_id = cc.id
            JOIN 
                buyers_semarang b ON mcp.buyer_id = b.id
        ";
        
        // Add buyer filter if set
        if (isset($_GET['buyer_id']) && !empty($_GET['buyer_id'])) {
            $where_clauses[] = "mcp.buyer_id = ?";
            $params[] = intval($_GET['buyer_id']);
            $param_types .= "i";
        }
        
        // Add status filter if set
        if (isset($_GET['status']) && !empty($_GET['status'])) {
            $where_clauses[] = "csi.status = ?";
            $params[] = $_GET['status'];
            $param_types .= "s";
        }
        
        // Add where clause if any filters are set
        if (!empty($where_clauses)) {
            $query .= " WHERE " . implode(" AND ", $where_clauses);
        }
        
        // Add order by for rack_no alphanumeric sorting
        $query .= " ORDER BY b.nama_buyer, mcp.buyer_id, mcp.code_color, cc.component_name, 
                    CASE 
                        WHEN rack_no REGEXP '^[A-Za-z]\\.[0-9]+$' THEN 
                            CONCAT(SUBSTRING_INDEX(rack_no, '.', 1), 
                                   LPAD(SUBSTRING_INDEX(rack_no, '.', -1), 5, '0'))
                        ELSE rack_no
                    END";
        
        // Prepare and execute the query
        $stmt = $conn->prepare($query);
        
        if (!empty($params)) {
            $stmt->bind_param($param_types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        // Group results by buyer and color
        $grouped_data = [];
        while ($row = $result->fetch_assoc()) {
            $buyer_id = $row['buyer_id'];
            $color_id = $row['color_id'];
            
            if (!isset($grouped_data[$buyer_id])) {
                $grouped_data[$buyer_id] = [
                    'buyer_name' => $row['nama_buyer'],
                    'kode_buyer' => $row['kode_buyer'],
                    'colors' => []
                ];
            }
            
            if (!isset($grouped_data[$buyer_id]['colors'][$color_id])) {
                $grouped_data[$buyer_id]['colors'][$color_id] = [
                    'color_id' => $row['color_id'],
                    'code_color' => $row['code_color'],
                    'color_description' => $row['color_description'],
                    'kode_warna_hex' => $row['kode_warna_hex'],
                    'components' => []
                ];
            }
            
            $grouped_data[$buyer_id]['colors'][$color_id]['components'][] = $row;
        }
        
        if (empty($grouped_data)):
        ?>
            <div class="bg-yellow-100 border-l-4 border-yellow-400 text-yellow-800 p-4 rounded-lg shadow-inner">
                <p class="text-center font-medium">
                    <i class="fas fa-info-circle mr-2"></i>Tidak ada data yang ditemukan sesuai filter Anda.
                </p>
            </div>
        <?php else: ?>
            <?php foreach ($grouped_data as $buyer): ?>
                <div class="mb-6">
                    <h4 class="text-base sm:text-lg font-bold text-purple-800 mb-2 bg-purple-50 p-3 rounded-lg border-l-4 border-purple-500">
                        <i class="fas fa-user-tie mr-2"></i>
                        <?php echo htmlspecialchars($buyer['buyer_name']); ?> 
                        <span class="text-xs sm:text-sm text-purple-600">(<?php echo htmlspecialchars($buyer['kode_buyer']); ?>)</span>
                    </h4>
                    
                    <?php foreach ($buyer['colors'] as $color): ?>
                        <div class="mb-4 border border-gray-200 rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow duration-200">
                            <div class="flex items-center p-3 sm:p-4 border-b border-gray-200" style="background-color: <?php echo htmlspecialchars($color['kode_warna_hex']); ?>20;">
                                <div class="flex-shrink-0 w-6 h-6 sm:w-8 sm:h-8 rounded-full mr-2 sm:mr-3 border-2 border-gray-300" style="background-color: <?php echo htmlspecialchars($color['kode_warna_hex']); ?>;"></div>
                                <div class="flex-grow">
                                    <h5 class="font-bold text-sm sm:text-base text-gray-800">
                                        <?php echo htmlspecialchars($buyer['kode_buyer'] . ' ' . $color['code_color']); ?>
                                    </h5>
                                    <p class="text-xs sm:text-sm text-gray-600">
                                        <?php echo htmlspecialchars($color['color_description']); ?>
                                    </p>
                                </div>
                            </div>
                            
                            <!-- Mobile View (Card Style) -->
                            <div class="block sm:hidden">
                                <?php
                                // Sort the components by rack_no using a natural sort function
                                $components = $color['components'];
                                usort($components, function($a, $b) {
                                    return strnatcmp($a['rack_no'], $b['rack_no']);
                                });
                                
                                foreach ($components as $component): 
                                ?>
                                    <div class="border-b border-gray-200 p-3 hover:bg-gray-50 transition-colors duration-150">
                                        <div class="flex justify-between items-start mb-2">
                                            <div class="font-medium text-gray-900 text-sm"><?php echo htmlspecialchars($component['component_name']); ?></div>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium
                                                <?php 
                                                switch ($component['status']) {
                                                    case 'Tersedia': echo 'bg-green-100 text-green-800'; break;
                                                    case 'Dipinjam': echo 'bg-blue-100 text-blue-800'; break;
                                                    case 'Rusak': echo 'bg-red-100 text-red-800'; break;
                                                    case 'Expired': echo 'bg-gray-100 text-gray-800'; break;
                                                    case 'Renew': echo 'bg-purple-100 text-purple-800'; break;
                                                }
                                                ?>">
                                                <?php echo htmlspecialchars($component['status']); ?>
                                            </span>
                                        </div>
                                        
                                        <div class="grid grid-cols-2 gap-1 text-xs mb-2">
                                            <div>
                                                <span class="text-gray-500">Kode Barang:</span>
                                                <div class="bg-gray-100 text-gray-800 px-2 py-1 rounded-md font-mono mt-1 break-all">
                                                    <?php echo htmlspecialchars($component['kode_barang']); ?>
                                                </div>
                                            </div>
                                            <div>
                                                <span class="text-gray-500">Rack No:</span>
                                                <div class="mt-1"><?php echo htmlspecialchars($component['rack_no']); ?></div>
                                            </div>
                                            <div class="mt-1">
                                                <span class="text-gray-500">Lokasi:</span>
                                                <div class="mt-1"><?php echo htmlspecialchars($component['lokasi']); ?></div>
                                            </div>
                                            <div class="mt-1">
                                                <span class="text-gray-500">Kadaluarsa:</span>
                                                <div class="mt-1">
                                                <?php 
                                                if ($component['tanggal_kedaluwarsa']) {
                                                    $expiry_date = new DateTime($component['tanggal_kedaluwarsa']);
                                                    $today = new DateTime();
                                                    $interval = $today->diff($expiry_date);
                                                    $days_remaining = $expiry_date > $today ? $interval->days : -$interval->days;
                                                    
                                                    echo date('d M Y', strtotime($component['tanggal_kedaluwarsa']));
                                                    
                                                    if ($days_remaining < 0) {
                                                        echo ' <span class="text-red-500 font-semibold">(Kadaluarsa)</span>';
                                                    } elseif ($days_remaining <= 10) {
                                                        echo ' <span class="text-yellow-600 font-semibold">(' . $days_remaining . ' hari)</span>';
                                                    }
                                                } else {
                                                    echo '-';
                                                }
                                                ?>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Action Buttons for Mobile -->
                                        <div class="mt-2 flex justify-end">
                                            <?php if ($component['status'] != 'Renew'): ?>
                                                <form method="post" action="" class="inline-block">
                                                    <input type="hidden" name="stock_item_id" value="<?php echo $component['stock_id']; ?>">
                                                    <button type="submit" name="renew_item" class="text-purple-600 hover:text-purple-900 bg-purple-100 px-3 py-1 rounded-md text-xs font-medium shadow-sm hover:shadow">
                                                        <i class="fas fa-sync-alt mr-1"></i>Renew
                                                    </button>
                                                </form>
                                            <?php else: ?>
                                                <form method="post" action="" class="inline-block">
                                                    <input type="hidden" name="stock_item_id" value="<?php echo $component['stock_id']; ?>">
                                                    <button type="submit" name="execute_renew" class="text-green-600 hover:text-green-900 bg-green-100 px-3 py-1 rounded-md text-xs font-medium shadow-sm hover:shadow">
                                                        <i class="fas fa-check mr-1"></i>Lakukan
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- Desktop View (Table) -->
                            <div class="hidden sm:block 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">Component</th>
                                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>
                                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rack No</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">Lokasi</th>
                                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Kadaluarsa</th>
                                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white divide-y divide-gray-200">
                                        <?php
                                        // Sort the components by rack_no using a natural sort function
                                        $components = $color['components'];
                                        usort($components, function($a, $b) {
                                            return strnatcmp($a['rack_no'], $b['rack_no']);
                                        });
                                        
                                        foreach ($components as $component): 
                                        ?>
                                            <tr class="hover:bg-gray-50 transition-colors duration-150">
                                                <td class="px-3 py-3 whitespace-nowrap text-sm font-medium text-gray-900">
                                                    <?php echo htmlspecialchars($component['component_name']); ?>
                                                </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 htmlspecialchars($component['kode_barang']); ?>
                                                    </span>
                                                </td>
                                                <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                                    <?php echo htmlspecialchars($component['rack_no']); ?>
                                                </td>
                                                <td class="px-3 py-3 whitespace-nowrap">
                                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium
                                                        <?php 
                                                        switch ($component['status']) {
                                                            case 'Tersedia': echo 'bg-green-100 text-green-800'; break;
                                                            case 'Dipinjam': echo 'bg-blue-100 text-blue-800'; break;
                                                            case 'Rusak': echo 'bg-red-100 text-red-800'; break;
                                                            case 'Expired': echo 'bg-gray-100 text-gray-800'; break;
                                                            case 'Renew': echo 'bg-purple-100 text-purple-800'; break;
                                                        }
                                                        ?>">
                                                        <?php echo htmlspecialchars($component['status']); ?>
                                                    </span>
                                                </td>
                                                <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                                    <?php echo htmlspecialchars($component['lokasi']); ?>
                                                </td>
                                                <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                                    <?php 
                                                    if ($component['tanggal_kedaluwarsa']) {
                                                        $expiry_date = new DateTime($component['tanggal_kedaluwarsa']);
                                                        $today = new DateTime();
                                                        $interval = $today->diff($expiry_date);
                                                        $days_remaining = $expiry_date > $today ? $interval->days : -$interval->days;
                                                        
                                                        echo date('d M Y', strtotime($component['tanggal_kedaluwarsa']));
                                                        
                                                        if ($days_remaining < 0) {
                                                            echo ' <span class="text-red-500 font-semibold">(Kadaluarsa)</span>';
                                                        } elseif ($days_remaining <= 10) {
                                                            echo ' <span class="text-yellow-600 font-semibold">(' . $days_remaining . ' hari)</span>';
                                                        }
                                                    } else {
                                                        echo '-';
                                                    }
                                                    ?>
                                                </td>
                                                <td class="px-3 py-3 whitespace-nowrap text-right text-sm font-medium">
                                                    <?php if ($component['status'] != 'Renew'): ?>
                                                        <form method="post" action="" class="inline-block">
                                                            <input type="hidden" name="stock_item_id" value="<?php echo $component['stock_id']; ?>">
                                                            <button type="submit" name="renew_item" class="text-purple-600 hover:text-purple-900 bg-purple-100 px-3 py-1 rounded-md text-xs font-medium shadow-sm hover:shadow">
                                                                <i class="fas fa-sync-alt mr-1"></i>Renew
                                                            </button>
                                                        </form>
                                                    <?php else: ?>
                                                        <form method="post" action="" class="inline-block">
                                                            <input type="hidden" name="stock_item_id" value="<?php echo $component['stock_id']; ?>">
                                                            <button type="submit" name="execute_renew" class="text-green-600 hover:text-green-900 bg-green-100 px-3 py-1 rounded-md text-xs font-medium shadow-sm hover:shadow">
                                                                <i class="fas fa-check mr-1"></i>Lakukan
                                                            </button>
                                                        </form>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <!-- Renew History Modal -->
    <div id="renew-history-modal" class="fixed inset-0 z-50 hidden overflow-auto bg-black bg-opacity-50 flex items-center justify-center p-2 sm:p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-6xl w-full mx-auto">
            <div class="flex justify-between items-center border-b p-3 sm:p-4 bg-purple-50">
                <h3 class="text-lg sm:text-xl font-semibold text-gray-800">
                    <i class="fas fa-history text-purple-600 mr-2"></i>Renew Code History
                </h3>
                <button onclick="closeRenewHistoryModal()" class="text-gray-500 hover:text-gray-700 transition-colors duration-150">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-2 sm:p-4">
                <div id="renew-history-content" class="overflow-x-auto">
                    <!-- History data will be loaded here via AJAX -->
                    <div class="text-center py-8">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-purple-500"></div>
                        <p class="mt-2 text-gray-600">Loading history data...</p>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-3 py-2 sm:px-6 sm:py-3 sm:flex sm:flex-row-reverse rounded-b-lg">
                <button type="button" onclick="closeRenewHistoryModal()" class="w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm transition-colors duration-150">
                    Close
                </button>
            </div>
        </div>
    </div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Check for expired items and highlight them
    const expiryDates = document.querySelectorAll('.expiry-date');
    const today = new Date();
    
    expiryDates.forEach(function(element) {
        const expiryDate = new Date(element.dataset.date);
        const daysRemaining = Math.floor((expiryDate - today) / (1000 * 60 * 60 * 24));
        
        if (daysRemaining < 0) {
            element.classList.add('text-red-500');
            element.innerHTML += ' <span class="font-medium">(Kadaluarsa)</span>';
        } else if (daysRemaining <= 10) {
            element.classList.add('text-yellow-600');
            element.innerHTML += ` <span class="font-medium">(${daysRemaining} hari)</span>`;
        }
    });
});

// Function to clear filters
function clearFilters() {
    document.getElementById('buyer_filter').value = '';
    document.getElementById('status_filter').value = '';
    document.getElementById('filter_form').submit();
}

// Function to view all renew history
function viewAllRenewHistory() {
    // Show modal
    document.getElementById('renew-history-modal').classList.remove('hidden');
    
    // Fetch history data
    fetch('get_all_renew_history_it.php')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                document.getElementById('renew-history-content').innerHTML = `
                    <div class="bg-red-100 border-l-4 border-red-400 text-red-700 p-4 rounded-lg">
                        <p><i class="fas fa-exclamation-circle mr-2"></i>${data.error}</p>
                    </div>
                `;
                return;
            }
            
            // Build history content
            const historyItems = data.history;
            
            let content = `
                <div class="mb-4">
                    <h4 class="text-base sm:text-lg font-semibold text-gray-800 mb-3 sm:mb-4">
                        <i class="fas fa-clock-rotate-left text-purple-600 mr-2"></i>All Renewal History
                    </h4>
                    
                    <div class="mb-4">
                        <input type="text" id="search-history" placeholder="Search by code, buyer, or color..." 
                               class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-500">
                    </div>
            `;
            
            if (historyItems.length === 0) {
                content += `
                    <div class="bg-yellow-100 border-l-4 border-yellow-400 text-yellow-800 p-4 rounded-lg">
                        <p class="text-center"><i class="fas fa-info-circle mr-2"></i>No renewal history found.</p>
                    </div>
                `;
            } else {
                // Mobile version (card layout)
                content += `
                    <div class="block sm:hidden">
                `;
                
                historyItems.forEach(item => {
                    const originalDate = item.tanggal_pembuatan ? new Date(item.tanggal_pembuatan).toLocaleDateString('id-ID') : '-';
                    const expiryDate = item.tanggal_kedaluwarsa ? new Date(item.tanggal_kedaluwarsa).toLocaleDateString('id-ID') : '-';
                    
                    content += `
                        <div class="mb-4 border border-gray-200 rounded-lg p-3 hover:shadow-md transition-shadow duration-200">
                            <div class="flex justify-between mb-2">
                                <div class="font-medium text-sm">${item.nama_buyer} (${item.kode_buyer})</div>
                                <div class="text-xs text-gray-500">${item.formatted_renewed_date}</div>
                            </div>
                            
                            <div class="grid grid-cols-2 gap-2 text-xs mb-2">
                                <div>
                                    <span class="text-gray-500">Color:</span>
                                    <div class="mt-1 font-medium">${item.code_color}</div>
                                </div>
                                <div>
                                    <span class="text-gray-500">Component:</span>
                                    <div class="mt-1">${item.component_name}</div>
                                </div>
                            </div>
                            
                            <div class="grid grid-cols-2 gap-2 text-xs mb-2">
                                <div>
                                    <span class="text-gray-500">Previous Code:</span>
                                    <div class="bg-gray-100 text-gray-800 px-2 py-1 rounded-md font-mono mt-1 break-all">
                                        ${item.kode_barang}
                                    </div>
                                </div>
                                <div>
                                    <span class="text-gray-500">New Code:</span>
                                    <div class="bg-purple-100 text-purple-800 px-2 py-1 rounded-md font-mono mt-1 break-all">
                                        ${item.new_code}
                                    </div>
                                </div>
                            </div>
                            
                            <div class="grid grid-cols-2 gap-2 text-xs">
                                <div>
                                    <span class="text-gray-500">Original Creation:</span>
                                    <div class="mt-1">${originalDate}</div>
                                </div>
                                <div>
                                    <span class="text-gray-500">Original Expiry:</span>
                                    <div class="mt-1">${expiryDate}</div>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                content += `
                    </div>
                `;
                
                // Desktop version (table layout)
                content += `
                    <div class="hidden sm:block">
                        <table class="min-w-full divide-y divide-gray-200" id="history-table">
                            <thead class="bg-purple-50">
                                <tr>
                                    <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</th>
                                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>
                                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Previous 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">Renewal Date</th>
                                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Original Creation</th>
                                    <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Original Expiry</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                `;
                
                historyItems.forEach(item => {
                    const originalDate = item.tanggal_pembuatan ? new Date(item.tanggal_pembuatan).toLocaleDateString('id-ID') : '-';
                    const expiryDate = item.tanggal_kedaluwarsa ? new Date(item.tanggal_kedaluwarsa).toLocaleDateString('id-ID') : '-';
                    
                    content += `
                        <tr class="hover:bg-gray-50 transition-colors duration-150">
                            <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                ${item.nama_buyer} (${item.kode_buyer})
                            </td>
                            <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                ${item.code_color}
                            </td>
                            <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                ${item.component_name}
                            </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">
                                    ${item.kode_barang}
                                </span>
                            </td>
                            <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                <span class="bg-purple-100 text-purple-800 px-2 py-1 rounded-md font-mono text-xs">
                                    ${item.new_code}
                                </span>
                            </td>
                            <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                ${item.formatted_renewed_date}
                            </td>
                            <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                ${originalDate}
                            </td>
                            <td class="px-3 py-3 whitespace-nowrap text-sm text-gray-500">
                                ${expiryDate}
                            </td>
                        </tr>
                    `;
                });
                
                content += `
                            </tbody>
                        </table>
                    </div>
                `;
            }
            
            // Update modal content
            document.getElementById('renew-history-content').innerHTML = content;
            
            // Add search functionality
            document.getElementById('search-history').addEventListener('keyup', function() {
                const searchTerm = this.value.toLowerCase();
                
                // For desktop table
                const tableRows = document.querySelectorAll('#history-table tbody tr');
                tableRows.forEach(function(row) {
                    const text = row.textContent.toLowerCase();
                    if (text.includes(searchTerm)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
                
                // For mobile cards
                const cards = document.querySelectorAll('#renew-history-content > div > div.block.sm\\:hidden > div');
                cards.forEach(function(card) {
                    const text = card.textContent.toLowerCase();
                    if (text.includes(searchTerm)) {
                        card.style.display = '';
                    } else {
                        card.style.display = 'none';
                    }
                });
            });
        })
        .catch(error => {
            document.getElementById('renew-history-content').innerHTML = `
                <div class="bg-red-100 border-l-4 border-red-400 text-red-700 p-4 rounded-lg">
                    <p><i class="fas fa-exclamation-triangle mr-2"></i>Error loading history: ${error.message}</p>
                </div>
            `;
        });
}

// Function to close renew history modal
function closeRenewHistoryModal() {
    document.getElementById('renew-history-modal').classList.add('hidden');
}
</script>

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