<!-- stok_color_admin.php -->
<?php
// Start session
session_start();

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

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

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

// Check if account is active, redirect to logout if not
if ($admin_data['status'] == 'nonactive') {
    // Log this attempt
    error_log("Nonactive admin attempted to access stock color data: " . $_SESSION['username']);
    
    // Clear all session variables
    $_SESSION = array();
    
    // Destroy the session
    session_destroy();
    
    // Redirect to login with message
    header("Location: ../login.php?error=inactive");
    exit();
}

// 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 
        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
        WHERE (status = 'Tersedia' OR status = 'Renew')
        AND tanggal_kedaluwarsa < '$today'
    ");
    $expired = $expired_result->fetch_assoc()['count'];
    
    if ($expired > 0) {
        // Create a notice for admin
        return "There are $expired expired items that need renewal. <a href='auto_renew_expired.php' class='text-blue-600 hover:underline'>Click here to auto-renew all</a>";
    }
    return "";
}

// Log activity
log_activity($conn, $admin_id, 'admin', 'Stock Color Access', 'Admin 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 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 csi
            JOIN master_color_panel 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
        $history_stmt = $conn->prepare("
            INSERT INTO renew_code_history 
            (original_id, color_id, component_id, kode_barang, stock_number, lokasi, qr_code, 
            tanggal_pembuatan, tanggal_kedaluwarsa, keterangan, renewed_date) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $history_stmt->bind_param(
            "iiisisssss", 
            $stock_item_id, 
            $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
            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 
            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, $admin_id, 'admin', 'Renew Color Item', "Admin 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 for filter
$buyer_query = "SELECT id, nama_buyer FROM buyers ORDER BY nama_buyer";
$buyer_result = $conn->query($buyer_query);

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

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

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

<!-- Main Content Area -->
<main class="flex-1 p-2 sm:p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6 mb-4 sm:mb-6">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center">
            <div>
                <h2 class="text-xl sm:text-2xl font-bold text-gray-800 mb-2 sm:mb-4">Stock Color Management</h2>
                <p class="text-gray-600 text-sm sm:text-base">Manage color stock items and process renewals</p>
            </div>
            <div class="mt-3 sm:mt-0">
                <button type="button" onclick="viewAllRenewHistory()" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 text-sm sm:text-base rounded-md transition duration-150 ease-in-out">
                    <i class="fas fa-history mr-2"></i>History
                </button>
            </div>
        </div>
    </div>
    
    <?php if (!empty($expiry_notice)): ?>
    <div class="bg-yellow-100 border border-yellow-400 text-yellow-700 px-3 py-2 sm:px-4 sm:py-3 rounded relative mb-4 sm:mb-6" role="alert">
        <span class="block sm:inline"><?php echo $expiry_notice; ?></span>
    </div>
    <?php endif; ?>
    
    <?php if (isset($success_message)): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-3 py-2 sm:px-4 sm:py-3 rounded relative mb-4 sm:mb-6" role="alert">
        <strong class="font-bold">Success!</strong>
        <span class="block sm:inline"><?php echo $success_message; ?></span>
    </div>
    <?php endif; ?>
    
    <?php if (isset($error_message)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-3 py-2 sm:px-4 sm:py-3 rounded relative mb-4 sm:mb-6" role="alert">
        <strong class="font-bold">Error!</strong>
        <span class="block sm:inline"><?php echo $error_message; ?></span>
    </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">Filter Data</h3>
        
        <form id="filter_form" method="get" action="">
            <div class="grid grid-cols-1 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-blue-500 focus:border-blue-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-blue-500 focus:border-blue-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">
                <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 text-sm rounded-md transition duration-150 ease-in-out w-full sm:w-auto">
                    <i class="fas fa-filter mr-2"></i>Terapkan Filter
                </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">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 csi
            JOIN 
                master_color_panel mcp ON csi.color_id = mcp.id
            JOIN 
                color_components cc ON csi.component_id = cc.id
            JOIN 
                buyers 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']; // Group by actual buyer_id, not name
            $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 text-yellow-800 p-4 rounded-md">
                <p class="text-center font-medium">No data found matching your filters.</p>
            </div>
        <?php else: ?>
            <?php foreach ($grouped_data as $buyer): ?>
                <div class="mb-6">
                    <h4 class="text-base sm:text-lg font-bold text-blue-800 mb-2 bg-blue-50 p-2 rounded">
                        <?php echo htmlspecialchars($buyer['buyer_name']); ?> 
                        <span class="text-xs sm:text-sm text-blue-600">(<?php echo htmlspecialchars($buyer['kode_buyer']); ?>)</span>
                    </h4>
                    
                    <?php foreach ($buyer['colors'] as $color): ?>
                        <div class="mb-4 border border-gray-200 rounded-md overflow-hidden">
                            <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" 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">
                                        <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">(Kadaluarsa)</span>';
                                                    } elseif ($days_remaining <= 10) {
                                                        echo ' <span class="text-yellow-600">(' . $days_remaining . ' hari)</span>';
                                                    }
                                                } else {
                                                    echo '-';
                                                }
                                                ?>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Important: Fixed 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-indigo-600 hover:text-indigo-900 bg-indigo-100 px-3 py-1 rounded-md text-xs">
                                                        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">
                                                        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>
                                                <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">(Kadaluarsa)</span>';
                                                        } elseif ($days_remaining <= 10) {
                                                            echo ' <span class="text-yellow-600">(' . $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-indigo-600 hover:text-indigo-900 bg-indigo-100 px-2 py-1 rounded-md text-xs">
                                                                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-2 py-1 rounded-md text-xs">
                                                                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">
                <h3 class="text-lg sm:text-xl font-semibold text-gray-800">Renew Code History</h3>
                <button onclick="closeRenewHistoryModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></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-blue-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-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    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 view all renew history
function viewAllRenewHistory() {
    // Show modal
    document.getElementById('renew-history-modal').classList.remove('hidden');
    
    // Fetch history data
    fetch('get_all_renew_history.php')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                document.getElementById('renew-history-content').innerHTML = `
                    <div class="bg-red-100 text-red-700 p-4 rounded-md">
                        <p>${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">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-blue-500 focus:border-blue-500">
                    </div>
            `;
            
            if (historyItems.length === 0) {
                content += `
                    <div class="bg-yellow-100 text-yellow-800 p-4 rounded-md">
                        <p class="text-center">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-md p-3">
                            <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">${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-gray-100 text-gray-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-gray-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>
                            <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-gray-100 text-gray-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 text-red-700 p-4 rounded-md">
                    <p>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_admin/footer.php'; ?>