<?php
// Start session
session_start();

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

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

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

// Set page title
$page_title = "Change Date Management";

// Log activity
create_audit_log($conn, 'Change Date Page Access', $it_id, 'it', 'IT user accessed change date page');

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    header('Content-Type: application/json');
    
    $action = $_POST['ajax_action'];
    
    // Get all items by color_id
    if ($action === 'get_items') {
        $color_id = (int)$_POST['color_id'];
        
        $query = "
            SELECT 
                csi.id,
                csi.kode_barang,
                csi.status,
                csi.rack_no,
                csi.tanggal_pembuatan,
                csi.tanggal_kedaluwarsa,
                csi.pernah_dipinjam,
                csi.lokasi,
                csi.component_id,
                mcp.code_color,
                b.nama_buyer,
                col.nama_collection,
                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 collections col ON mcp.collection_id = col.id
            JOIN color_components cc ON csi.component_id = cc.id
            WHERE csi.color_id = ?
            ORDER BY cc.component_name, csi.kode_barang
        ";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $color_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $items = [];
        $color_info = [];
        
        while ($row = $result->fetch_assoc()) {
            if (empty($color_info)) {
                $color_info = [
                    'buyer' => $row['nama_buyer'],
                    'color_code' => $row['code_color'],
                    'collection' => $row['nama_collection']
                ];
            }
            $items[] = $row;
        }
        $stmt->close();
        
        echo json_encode([
            'success' => true, 
            'items' => $items,
            'color_info' => $color_info
        ]);
        exit();
    }
    
    // Save date changes for ALL items in the color code
    if ($action === 'save_changes') {
        $color_id = (int)$_POST['color_id'];
        $tanggal_pembuatan = $_POST['tanggal_pembuatan'];
        $tanggal_kedaluwarsa = $_POST['tanggal_kedaluwarsa'];
        $keterangan = isset($_POST['keterangan']) ? trim($_POST['keterangan']) : '';
        
        // Validate dates
        $pembuatan = new DateTime($tanggal_pembuatan);
        $kedaluwarsa = new DateTime($tanggal_kedaluwarsa);
        
        if ($kedaluwarsa <= $pembuatan) {
            echo json_encode([
                'success' => false, 
                'message' => 'Tanggal kedaluwarsa harus setelah tanggal pembuatan!'
            ]);
            exit();
        }
        
        // Start transaction
        $conn->begin_transaction();
        
        try {
            // Get all items that will be updated (for logging)
            $get_items_stmt = $conn->prepare("
                SELECT csi.kode_barang, cc.component_name
                FROM color_stock_items csi
                JOIN color_components cc ON csi.component_id = cc.id
                WHERE csi.color_id = ?
                ORDER BY cc.component_name, csi.kode_barang
            ");
            $get_items_stmt->bind_param("i", $color_id);
            $get_items_stmt->execute();
            $items_result = $get_items_stmt->get_result();
            
            $affected_items = [];
            $component_count = [];
            
            while ($item = $items_result->fetch_assoc()) {
                $affected_items[] = $item['kode_barang'];
                if (!isset($component_count[$item['component_name']])) {
                    $component_count[$item['component_name']] = 0;
                }
                $component_count[$item['component_name']]++;
            }
            $get_items_stmt->close();
            
            $total_affected = count($affected_items);
            
            if ($total_affected === 0) {
                throw new Exception("Tidak ada item yang ditemukan untuk diupdate");
            }
            
            // Get color info for logging
            $color_info_stmt = $conn->prepare("
                SELECT mcp.code_color, b.nama_buyer, col.nama_collection
                FROM master_color_panel mcp
                JOIN buyers b ON mcp.buyer_id = b.id
                JOIN collections col ON mcp.collection_id = col.id
                WHERE mcp.id = ?
            ");
            $color_info_stmt->bind_param("i", $color_id);
            $color_info_stmt->execute();
            $color_info = $color_info_stmt->get_result()->fetch_assoc();
            $color_info_stmt->close();
            
            // Update ALL items in this color code
            $update_stmt = $conn->prepare("
                UPDATE color_stock_items 
                SET tanggal_pembuatan = ?, 
                    tanggal_kedaluwarsa = ?
                WHERE color_id = ?
            ");
            
            $update_stmt->bind_param("ssi", $tanggal_pembuatan, $tanggal_kedaluwarsa, $color_id);
            $update_stmt->execute();
            $rows_affected = $update_stmt->affected_rows;
            $update_stmt->close();
            
            // Create component summary for log
            $component_summary = [];
            foreach ($component_count as $comp_name => $count) {
                $component_summary[] = "{$comp_name} ({$count} items)";
            }
            $component_summary_text = implode(', ', $component_summary);
            
            // Log the change
            $log_details = "IT user changed dates for entire color code: {$color_info['nama_buyer']} - {$color_info['code_color']} ({$color_info['nama_collection']}). " .
                          "Total items affected: {$total_affected} across components: {$component_summary_text}. " .
                          "New dates - Pembuatan: {$tanggal_pembuatan}, Kedaluwarsa: {$tanggal_kedaluwarsa}";
            
            if (!empty($keterangan)) {
                $log_details .= ". Keterangan: {$keterangan}";
            }
            
            create_audit_log($conn, 'Change Date Batch Update (All Components)', $it_id, 'it', $log_details);
            
            // Commit transaction
            $conn->commit();
            
            echo json_encode([
                'success' => true, 
                'message' => "✅ Berhasil mengubah tanggal untuk {$total_affected} items di semua component!",
                'affected_items' => $affected_items,
                'total_affected' => $total_affected,
                'component_summary' => $component_summary
            ]);
            
        } catch (Exception $e) {
            $conn->rollback();
            error_log("Error in change_date.php: " . $e->getMessage());
            
            echo json_encode([
                'success' => false, 
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ]);
        }
        
        exit();
    }
}

// Get all color panels for the dropdown
$color_panels_query = "
    SELECT DISTINCT
        mcp.id as color_id,
        mcp.code_color,
        b.nama_buyer,
        col.nama_collection,
        (SELECT COUNT(*) FROM color_stock_items WHERE color_id = mcp.id) as total_items
    FROM master_color_panel mcp
    JOIN buyers b ON mcp.buyer_id = b.id
    JOIN collections col ON mcp.collection_id = col.id
    WHERE EXISTS (SELECT 1 FROM color_stock_items WHERE color_id = mcp.id)
    ORDER BY b.nama_buyer, mcp.code_color
";
$color_panels_result = $conn->query($color_panels_query);

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

<!-- Main Content Area -->
<main class="flex-1 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-6 mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h2 class="text-2xl font-bold text-gray-800">
                    <i class="fas fa-calendar-alt mr-2 text-indigo-600"></i>
                    Change Date Management
                </h2>
                <p class="text-gray-600 mt-1">Ubah tanggal pembuatan dan kedaluwarsa untuk <strong>semua items</strong> dalam satu color code</p>
            </div>
            <div class="text-right">
                <p class="text-sm text-gray-500">IT Admin</p>
                <p class="text-lg font-medium text-gray-800"><?php echo htmlspecialchars($it_data['username']); ?></p>
            </div>
        </div>
    </div>

    <!-- Information Alert -->
    <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border-l-4 border-blue-500 p-4 mb-6 rounded-md shadow-sm">
        <div class="flex">
            <div class="flex-shrink-0">
                <svg class="h-6 w-6 text-blue-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                </svg>
            </div>
            <div class="ml-3 flex-1">
                <h3 class="text-sm font-semibold text-blue-800 mb-1">Informasi Penting:</h3>
                <ul class="text-sm text-blue-700 space-y-1">
                    <li>✅ <strong>Pilih 1 color code</strong> → Semua component & items akan tampil</li>
                    <li>✅ <strong>Pilih 1 item sebagai master</strong> → Form akan terisi otomatis</li>
                    <li>✅ <strong>Ubah tanggal & simpan</strong> → SEMUA items dalam color code tersebut akan berubah!</li>
                    <li>⚠️ <strong>Efisien:</strong> Tidak perlu ubah satu-satu component!</li>
                </ul>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-filter mr-2 text-blue-600"></i>
            Pilih Color Code
        </h3>
        
        <form id="filter-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="md:col-span-2">
                    <label for="color_panel" class="block text-sm font-medium text-gray-700 mb-2">
                        Color Panel <span class="text-red-500">*</span>
                    </label>
                    <select id="color_panel" name="color_panel" class="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm" required>
                        <option value="">-- Pilih Color Code --</option>
                        <?php while ($color = $color_panels_result->fetch_assoc()): ?>
                            <option value="<?php echo $color['color_id']; ?>" data-total="<?php echo $color['total_items']; ?>">
                                <?php echo htmlspecialchars($color['nama_buyer'] . ' - ' . $color['code_color'] . ' (' . $color['nama_collection'] . ') - ' . $color['total_items'] . ' items'); ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <div class="flex items-end">
                    <button type="submit" id="search-btn" class="w-full inline-flex items-center justify-center px-6 py-3 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all" disabled>
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                        </svg>
                        Tampilkan Semua Items
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Loading Indicator -->
    <div id="loading" class="hidden text-center py-12">
        <div class="inline-block animate-spin rounded-full h-16 w-16 border-b-4 border-blue-600"></div>
        <p class="mt-4 text-gray-600 font-medium">Memuat data...</p>
    </div>

    <!-- Results Section -->
    <div id="results-section" class="hidden">
        <!-- Color Info Card -->
        <div class="bg-gradient-to-r from-purple-500 via-indigo-500 to-blue-500 rounded-lg shadow-lg p-6 mb-6 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        <i class="fas fa-palette mr-2"></i>
                        Color Code Information
                    </h3>
                    <div id="color-info" class="space-y-1 text-sm">
                        <!-- Will be filled by JavaScript -->
                    </div>
                </div>
                <div class="text-right bg-white bg-opacity-20 rounded-lg p-4 backdrop-blur-sm">
                    <p class="text-sm opacity-90 font-medium">Total Items</p>
                    <p id="total-items" class="text-4xl font-bold mt-1">0</p>
                    <p class="text-xs opacity-75 mt-1">Semua Component</p>
                </div>
            </div>
        </div>

        <!-- Date Change Form -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800">
                    <i class="fas fa-edit mr-2 text-green-600"></i>
                    Ubah Tanggal (Berlaku untuk SEMUA Items)
                </h3>
                <div id="selected-master-info" class="text-sm text-gray-600 hidden">
                    <i class="fas fa-star text-yellow-500 mr-1"></i>
                    Master: <span id="master-code" class="font-semibold text-blue-600"></span>
                </div>
            </div>
            
            <form id="change-date-form" class="space-y-4">
                <input type="hidden" id="selected_color_id" name="selected_color_id">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="tanggal_pembuatan" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-calendar-plus mr-1 text-green-600"></i>
                            Tanggal Pembuatan Baru <span class="text-red-500">*</span>
                        </label>
                        <input type="date" id="tanggal_pembuatan" name="tanggal_pembuatan" class="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 text-sm" required>
                        <p class="text-xs text-gray-500 mt-1">Tanggal pembuatan color code</p>
                    </div>

                    <div>
                        <label for="tanggal_kedaluwarsa" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-calendar-times mr-1 text-red-600"></i>
                            Tanggal Kedaluwarsa Baru <span class="text-red-500">*</span>
                        </label>
                        <input type="date" id="tanggal_kedaluwarsa" name="tanggal_kedaluwarsa" class="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500 text-sm" required>
                        <p class="text-xs text-gray-500 mt-1">Tanggal kedaluwarsa color code</p>
                    </div>
                </div>

                <div>
                    <label for="keterangan_perubahan" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-comment mr-1 text-blue-600"></i>
                        Keterangan Perubahan (Opsional)
                    </label>
                    <textarea id="keterangan_perubahan" name="keterangan_perubahan" rows="3" class="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm" placeholder="Contoh: Update tanggal karena renewal stok, perbaikan data, dll..."></textarea>
                </div>

                <div class="flex justify-end space-x-3 pt-4">
                    <button type="button" id="preview-btn" class="inline-flex items-center px-6 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                            <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                            <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" />
                        </svg>
                        Preview Perubahan
                    </button>
                    
                    <button type="submit" id="save-btn" class="inline-flex items-center px-6 py-3 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                        </svg>
                        Simpan Perubahan
                    </button>
                </div>
            </form>
        </div>

        <!-- Items Table -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800">
                    <i class="fas fa-list mr-2 text-indigo-600"></i>
                    Daftar Semua Items (Pilih 1 sebagai Master)
                </h3>
                <div class="text-sm text-gray-600">
                    <i class="fas fa-info-circle mr-1 text-blue-500"></i>
                    Klik <strong>"Pilih"</strong> pada item untuk mengisi form
                </div>
            </div>
            
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gradient-to-r from-gray-50 to-gray-100">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rack</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tgl Pembuatan</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tgl Kedaluwarsa</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Pernah Dipinjam</th>
                        </tr>
                    </thead>
                    <tbody id="items-table-body" class="bg-white divide-y divide-gray-200">
                        <!-- Will be filled by JavaScript -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<!-- Preview Modal -->
<div id="preview-modal" class="fixed inset-0 z-50 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-900 opacity-75"></div>
        </div>

        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-6xl sm:w-full">
            <div class="bg-gradient-to-r from-blue-500 to-indigo-600 px-6 py-4">
                <h3 class="text-xl font-bold text-white flex items-center">
                    <svg class="h-6 w-6 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                    Preview Perubahan Tanggal
                </h3>
            </div>
            
            <div class="bg-white px-6 py-4">
                <div class="bg-gradient-to-r from-yellow-50 to-orange-50 border-l-4 border-yellow-500 p-4 mb-4">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <svg class="h-6 w-6 text-yellow-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <div class="ml-3 flex-1">
                            <h4 class="text-sm font-bold text-yellow-800 mb-1">PERHATIAN!</h4>
                            <p class="text-sm text-yellow-700">
                                <strong><span id="preview-total-items" class="text-lg">0</span> items</strong> dari <strong>SEMUA component</strong> akan diubah tanggalnya secara bersamaan!
                            </p>
                            <p class="text-xs text-yellow-600 mt-1">
                                ⚠️ Perubahan ini bersifat permanen dan tidak dapat dibatalkan!
                            </p>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-6 mb-6">
                    <div class="bg-gradient-to-br from-green-50 to-emerald-50 p-4 rounded-lg border-2 border-green-300 shadow-sm">
                        <div class="flex items-center mb-2">
                            <i class="fas fa-calendar-plus text-green-600 text-xl mr-2"></i>
                            <p class="text-xs text-gray-600 uppercase font-semibold">Tanggal Pembuatan Baru</p>
                        </div>
                        <p id="preview-pembuatan" class="text-2xl font-bold text-green-700"></p>
                    </div>
                    <div class="bg-gradient-to-br from-red-50 to-rose-50 p-4 rounded-lg border-2 border-red-300 shadow-sm">
                        <div class="flex items-center mb-2">
                            <i class="fas fa-calendar-times text-red-600 text-xl mr-2"></i>
                            <p class="text-xs text-gray-600 uppercase font-semibold">Tanggal Kedaluwarsa Baru</p>
                        </div>
                        <p id="preview-kedaluwarsa" class="text-2xl font-bold text-red-700"></p>
                        </div>
                </div>

                <div class="mb-4">
                    <h4 class="text-sm font-semibold text-gray-700 mb-3 flex items-center">
                        <i class="fas fa-chart-pie mr-2 text-indigo-600"></i>
                        Ringkasan Perubahan per Component
                    </h4>
                    <div id="component-summary" class="grid grid-cols-2 md:grid-cols-3 gap-3">
                        <!-- Will be filled by JavaScript -->
                    </div>
                </div>

                <div class="overflow-x-auto max-h-96 border-2 border-gray-200 rounded-lg shadow-inner">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gradient-to-r from-gray-100 to-gray-200 sticky top-0">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-bold text-gray-600 uppercase">Component</th>
                                <th class="px-4 py-3 text-left text-xs font-bold text-gray-600 uppercase">Kode</th>
                                <th class="px-4 py-3 text-left text-xs font-bold text-gray-600 uppercase">Status</th>
                                <th class="px-4 py-3 text-left text-xs font-bold text-gray-600 uppercase">Pembuatan Lama</th>
                                <th class="px-4 py-3 text-center text-xs font-bold text-gray-600 uppercase w-12">→</th>
                                <th class="px-4 py-3 text-left text-xs font-bold text-green-700 uppercase">Pembuatan Baru</th>
                                <th class="px-4 py-3 text-left text-xs font-bold text-gray-600 uppercase">Kedaluwarsa Lama</th>
                                <th class="px-4 py-3 text-center text-xs font-bold text-gray-600 uppercase w-12">→</th>
                                <th class="px-4 py-3 text-left text-xs font-bold text-red-700 uppercase">Kedaluwarsa Baru</th>
                            </tr>
                        </thead>
                        <tbody id="preview-table-body" class="bg-white divide-y divide-gray-200">
                            <!-- Will be filled by JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>
            
            <div class="bg-gray-50 px-6 py-4 flex flex-col sm:flex-row gap-3 sm:justify-end">
                <button type="button" id="close-preview" class="w-full sm:w-auto inline-flex justify-center items-center rounded-md border-2 border-gray-300 shadow-sm px-6 py-3 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all">
                    <i class="fas fa-times mr-2"></i>
                    Batal
                </button>
                <button type="button" id="confirm-save-from-preview" class="w-full sm:w-auto inline-flex justify-center items-center rounded-md border border-transparent shadow-sm px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-sm font-medium text-white hover:from-green-700 hover:to-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all">
                    <i class="fas fa-check-double mr-2"></i>
                    Konfirmasi & Simpan Semua
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Success/Error Notification -->
<div id="notification" class="fixed top-4 right-4 z-50 hidden">
    <div id="notification-content" class="bg-white rounded-lg shadow-2xl max-w-md transform transition-all">
        <!-- Will be filled by JavaScript -->
    </div>
</div>

<!-- JavaScript -->
<script>
// Global variables
let currentItems = [];
let currentColorInfo = {};
let selectedMasterItem = null;

// Format date to Indonesian
function formatDateIndo(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
    const day = date.getDate();
    const month = months[date.getMonth()];
    const year = date.getFullYear();
    return `${day} ${month} ${year}`;
}

// Show notification
function showNotification(type, message, autoClose = true) {
    const notification = document.getElementById('notification');
    const content = document.getElementById('notification-content');
    
    let icon, bgColor, textColor, borderColor;
    if (type === 'success') {
        icon = '<i class="fas fa-check-circle text-3xl"></i>';
        bgColor = 'bg-gradient-to-r from-green-50 to-emerald-50';
        textColor = 'text-green-800';
        borderColor = 'border-green-500';
    } else if (type === 'error') {
        icon = '<i class="fas fa-times-circle text-3xl"></i>';
        bgColor = 'bg-gradient-to-r from-red-50 to-rose-50';
        textColor = 'text-red-800';
        borderColor = 'border-red-500';
    } else if (type === 'warning') {
        icon = '<i class="fas fa-exclamation-triangle text-3xl"></i>';
        bgColor = 'bg-gradient-to-r from-yellow-50 to-orange-50';
        textColor = 'text-yellow-800';
        borderColor = 'border-yellow-500';
    } else {
        icon = '<i class="fas fa-info-circle text-3xl"></i>';
        bgColor = 'bg-gradient-to-r from-blue-50 to-indigo-50';
        textColor = 'text-blue-800';
        borderColor = 'border-blue-500';
    }
    
    content.innerHTML = `
        <div class="flex items-start ${bgColor} p-4 rounded-lg border-l-4 ${borderColor} shadow-lg">
            <div class="${textColor} mr-3">
                ${icon}
            </div>
            <div class="flex-1">
                <p class="${textColor} font-semibold text-sm leading-relaxed">${message}</p>
            </div>
            <button onclick="closeNotification()" class="ml-3 ${textColor} hover:opacity-75 transition-opacity">
                <i class="fas fa-times text-lg"></i>
            </button>
        </div>
    `;
    
    notification.classList.remove('hidden');
    
    if (autoClose) {
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 6000);
    }
}

function closeNotification() {
    document.getElementById('notification').classList.add('hidden');
}

// Enable search button when color panel is selected
document.getElementById('color_panel').addEventListener('change', function() {
    const searchBtn = document.getElementById('search-btn');
    searchBtn.disabled = !this.value;
    
    // Hide results section
    document.getElementById('results-section').classList.add('hidden');
    selectedMasterItem = null;
});

// Handle filter form submission
document.getElementById('filter-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const colorId = document.getElementById('color_panel').value;
    
    if (!colorId) {
        showNotification('error', 'Pilih color code terlebih dahulu');
        return;
    }
    
    loadItems(colorId);
});

// Load all items for a color code
function loadItems(colorId) {
    const loading = document.getElementById('loading');
    const resultsSection = document.getElementById('results-section');
    
    loading.classList.remove('hidden');
    resultsSection.classList.add('hidden');
    selectedMasterItem = null;
    
    const formData = new FormData();
    formData.append('ajax_action', 'get_items');
    formData.append('color_id', colorId);
    
    fetch('change_date.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        loading.classList.add('hidden');
        
        if (data.success && data.items.length > 0) {
            currentItems = data.items;
            currentColorInfo = data.color_info;
            
            // Store selected color ID
            document.getElementById('selected_color_id').value = colorId;
            
            // Display color info
            const colorInfoDiv = document.getElementById('color-info');
            colorInfoDiv.innerHTML = `
                <p class="text-lg"><strong>Buyer:</strong> ${data.color_info.buyer}</p>
                <p class="text-lg"><strong>Color Code:</strong> ${data.color_info.color_code}</p>
                <p class="text-sm opacity-90"><strong>Collection:</strong> ${data.color_info.collection}</p>
            `;
            
            // Display total items
            document.getElementById('total-items').textContent = data.items.length;
            
            // Group items by component for display
            const itemsByComponent = {};
            data.items.forEach(item => {
                if (!itemsByComponent[item.component_name]) {
                    itemsByComponent[item.component_name] = [];
                }
                itemsByComponent[item.component_name].push(item);
            });
            
            // Populate items table
            const tbody = document.getElementById('items-table-body');
            tbody.innerHTML = '';
            
            let globalIndex = 0;
            let componentIndex = 0;
            
            Object.keys(itemsByComponent).forEach(componentName => {
                const items = itemsByComponent[componentName];
                
                items.forEach((item, localIndex) => {
                    const row = document.createElement('tr');
                    row.className = componentIndex % 2 === 0 ? 'bg-white hover:bg-blue-50' : 'bg-gray-50 hover:bg-blue-50';
                    row.classList.add('transition-colors', 'cursor-pointer');
                    
                    const pernahDipinjamBadge = item.pernah_dipinjam == 1 
                        ? '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">Sudah</span>'
                        : '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Belum</span>';
                    
                    const statusBadge = item.status === 'Tersedia' 
                        ? '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">' + item.status + '</span>'
                        : item.status === 'Dipinjam'
                        ? '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">' + item.status + '</span>'
                        : item.status === 'Rusak'
                        ? '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">' + item.status + '</span>'
                        : '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">' + item.status + '</span>';
                    
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <button type="button" class="select-master-btn px-4 py-2 bg-blue-500 text-white text-xs font-semibold rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 transition-all" data-index="${globalIndex}">
                                <i class="fas fa-hand-pointer mr-1"></i> Pilih
                            </button>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">${globalIndex + 1}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700 font-semibold">${componentName}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-bold text-indigo-600">${item.kode_barang}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm">${statusBadge}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${item.rack_no || '-'}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${item.lokasi}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${formatDateIndo(item.tanggal_pembuatan)}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${formatDateIndo(item.tanggal_kedaluwarsa)}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm">${pernahDipinjamBadge}</td>
                    `;
                    tbody.appendChild(row);
                    
                    globalIndex++;
                });
                
                componentIndex++;
            });
            
            // Add event listeners to select buttons
            document.querySelectorAll('.select-master-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const index = parseInt(this.dataset.index);
                    selectMasterItem(index);
                });
            });
            
            resultsSection.classList.remove('hidden');
            
            // Scroll to results
            resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
            
            // Clear form
            document.getElementById('tanggal_pembuatan').value = '';
            document.getElementById('tanggal_kedaluwarsa').value = '';
            document.getElementById('keterangan_perubahan').value = '';
            document.getElementById('selected-master-info').classList.add('hidden');
            
        } else {
            showNotification('error', 'Tidak ada items ditemukan untuk color code ini');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        loading.classList.add('hidden');
        showNotification('error', 'Terjadi kesalahan saat memuat data items');
    });
}

// Select master item
function selectMasterItem(index) {
    selectedMasterItem = currentItems[index];
    
    // Fill form with selected item's dates
    document.getElementById('tanggal_pembuatan').value = selectedMasterItem.tanggal_pembuatan;
    document.getElementById('tanggal_kedaluwarsa').value = selectedMasterItem.tanggal_kedaluwarsa;
    
    // Show selected master info
    document.getElementById('master-code').textContent = selectedMasterItem.kode_barang;
    document.getElementById('selected-master-info').classList.remove('hidden');
    
    // Highlight selected row
    document.querySelectorAll('.select-master-btn').forEach((btn, i) => {
        if (i === index) {
            btn.classList.remove('bg-blue-500', 'hover:bg-blue-600');
            btn.classList.add('bg-green-500', 'hover:bg-green-600');
            btn.innerHTML = '<i class="fas fa-check mr-1"></i> Dipilih';
            btn.closest('tr').classList.add('bg-green-50', 'border-2', 'border-green-500');
        } else {
            btn.classList.remove('bg-green-500', 'hover:bg-green-600', 'border-2', 'border-green-500');
            btn.classList.add('bg-blue-500', 'hover:bg-blue-600');
            btn.innerHTML = '<i class="fas fa-hand-pointer mr-1"></i> Pilih';
            btn.closest('tr').classList.remove('bg-green-50', 'border-2', 'border-green-500');
        }
    });
    
    // Scroll to form
    document.getElementById('change-date-form').scrollIntoView({ behavior: 'smooth', block: 'center' });
    
    showNotification('success', `Master item dipilih: ${selectedMasterItem.kode_barang}. Silakan ubah tanggal jika diperlukan.`, true);
}

// Handle preview button
document.getElementById('preview-btn').addEventListener('click', function() {
    const tanggalPembuatan = document.getElementById('tanggal_pembuatan').value;
    const tanggalKedaluwarsa = document.getElementById('tanggal_kedaluwarsa').value;
    
    if (!tanggalPembuatan || !tanggalKedaluwarsa) {
        showNotification('error', 'Silakan isi tanggal pembuatan dan tanggal kedaluwarsa terlebih dahulu!');
        return;
    }
    
    // Validate dates
    const pembuatan = new Date(tanggalPembuatan);
    const kedaluwarsa = new Date(tanggalKedaluwarsa);
    
    if (kedaluwarsa <= pembuatan) {
        showNotification('error', 'Tanggal kedaluwarsa harus setelah tanggal pembuatan!');
        return;
    }
    
    // Show preview modal
    document.getElementById('preview-total-items').textContent = currentItems.length;
    document.getElementById('preview-pembuatan').textContent = formatDateIndo(tanggalPembuatan);
    document.getElementById('preview-kedaluwarsa').textContent = formatDateIndo(tanggalKedaluwarsa);
    
    // Create component summary
    const componentCounts = {};
    currentItems.forEach(item => {
        if (!componentCounts[item.component_name]) {
            componentCounts[item.component_name] = 0;
        }
        componentCounts[item.component_name]++;
    });
    
    const componentSummaryDiv = document.getElementById('component-summary');
    componentSummaryDiv.innerHTML = '';
    
    Object.keys(componentCounts).forEach(compName => {
        const count = componentCounts[compName];
        const summaryCard = document.createElement('div');
        summaryCard.className = 'bg-blue-50 border border-blue-200 rounded-lg p-3 text-center';
        summaryCard.innerHTML = `
            <p class="text-xs text-gray-600 font-medium">${compName}</p>
            <p class="text-2xl font-bold text-blue-700">${count}</p>
            <p class="text-xs text-gray-500">items</p>
        `;
        componentSummaryDiv.appendChild(summaryCard);
    });
    
    // Populate preview table
    const previewTbody = document.getElementById('preview-table-body');
    previewTbody.innerHTML = '';
    
    currentItems.forEach((item, index) => {
        const row = document.createElement('tr');
        row.className = index % 2 === 0 ? 'bg-white' : 'bg-gray-50';
        
        const statusClass = item.status === 'Tersedia' ? 'text-green-600' : item.status === 'Dipinjam' ? 'text-yellow-600' : 'text-gray-600';
        
        row.innerHTML = `
            <td class="px-4 py-2 text-xs font-semibold text-gray-700">${item.component_name}</td>
            <td class="px-4 py-2 text-xs font-bold text-indigo-600">${item.kode_barang}</td>
            <td class="px-4 py-2 text-xs ${statusClass}">${item.status}</td>
            <td class="px-4 py-2 text-xs text-gray-500">${formatDateIndo(item.tanggal_pembuatan)}</td>
            <td class="px-4 py-2 text-xs text-center text-blue-600"><i class="fas fa-arrow-right"></i></td>
            <td class="px-4 py-2 text-xs font-bold text-green-700">${formatDateIndo(tanggalPembuatan)}</td>
            <td class="px-4 py-2 text-xs text-gray-500">${formatDateIndo(item.tanggal_kedaluwarsa)}</td>
            <td class="px-4 py-2 text-xs text-center text-red-600"><i class="fas fa-arrow-right"></i></td>
            <td class="px-4 py-2 text-xs font-bold text-red-700">${formatDateIndo(tanggalKedaluwarsa)}</td>
        `;
        previewTbody.appendChild(row);
    });
    
    document.getElementById('preview-modal').classList.remove('hidden');
});

// Close preview modal
document.getElementById('close-preview').addEventListener('click', function() {
    document.getElementById('preview-modal').classList.add('hidden');
});

// Confirm save from preview
document.getElementById('confirm-save-from-preview').addEventListener('click', function() {
    document.getElementById('preview-modal').classList.add('hidden');
    document.getElementById('change-date-form').dispatchEvent(new Event('submit'));
});

// Handle form submission
document.getElementById('change-date-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const colorId = document.getElementById('selected_color_id').value;
    const tanggalPembuatan = document.getElementById('tanggal_pembuatan').value;
    const tanggalKedaluwarsa = document.getElementById('tanggal_kedaluwarsa').value;
    const keterangan = document.getElementById('keterangan_perubahan').value;
    
    if (!tanggalPembuatan || !tanggalKedaluwarsa) {
        showNotification('error', 'Silakan isi semua field tanggal yang required!');
        return;
    }
    
    // Validate dates
    const pembuatan = new Date(tanggalPembuatan);
    const kedaluwarsa = new Date(tanggalKedaluwarsa);
    
    if (kedaluwarsa <= pembuatan) {
        showNotification('error', 'Tanggal kedaluwarsa harus setelah tanggal pembuatan!');
        return;
    }
    
    // Confirm before saving
    const confirmMessage = `KONFIRMASI PERUBAHAN\n\n` +
                          `Apakah Anda yakin ingin mengubah tanggal untuk ${currentItems.length} items?\n\n` +
                          `Color: ${currentColorInfo.color_code}\n` +
                          `Buyer: ${currentColorInfo.buyer}\n\n` +
                          `⚠️ PERUBAHAN INI TIDAK DAPAT DIBATALKAN!`;
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    // Disable save button
    const saveBtn = document.getElementById('save-btn');
    const originalContent = saveBtn.innerHTML;
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Menyimpan...';
    
    // Send AJAX request
    const formData = new FormData();
    formData.append('ajax_action', 'save_changes');
    formData.append('color_id', colorId);
    formData.append('tanggal_pembuatan', tanggalPembuatan);
    formData.append('tanggal_kedaluwarsa', tanggalKedaluwarsa);
    formData.append('keterangan', keterangan);
    
    fetch('change_date.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', data.message, false);
            
            // Show component summary in notification
            if (data.component_summary && data.component_summary.length > 0) {
                setTimeout(() => {
                    const summaryText = data.component_summary.join(', ');
                    showNotification('info', `Detail: ${summaryText}`, true);
                }, 2000);
            }
            
            // Reload items to show updated data
            setTimeout(() => {
                loadItems(colorId);
            }, 3000);
            
        } else {
            showNotification('error', data.message, false);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('error', 'Terjadi kesalahan saat menyimpan perubahan. Silakan coba lagi.', false);
    })
    .finally(() => {
        // Re-enable save button
        saveBtn.disabled = false;
        saveBtn.innerHTML = originalContent;
    });
});

// Close modal when clicking outside
window.addEventListener('click', function(event) {
    const previewModal = document.getElementById('preview-modal');
    if (event.target === previewModal) {
        previewModal.classList.add('hidden');
    }
});
</script>

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