<?php
// Start session
session_start();

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

// Redirect if not Approval user
redirect_if_not_approval();

// Verify account is active
verify_active_status($conn);

// Get approval user data
$approval_id = $_SESSION['user_id'];
$jabatan = $_SESSION['jabatan'];

// Set page title
$page_title = "History Tanda Tangan";

// Get user's approval column based on jabatan
$column_mapping = [
    'K A Unit' => ['column' => 'ka_unit_approved_by', 'signature' => 'ka_unit_signature', 'date' => 'ka_unit_approved_at'],
    'Color Room' => ['column' => 'color_room_approved_by', 'signature' => 'color_room_signature', 'date' => 'color_room_approved_at'],
    'Akzonobel' => ['column' => 'akzonobel_approved_by', 'signature' => 'akzonobel_signature', 'date' => 'akzonobel_approved_at'],
    'Approved by' => ['column' => 'approved_by_approved_by', 'signature' => 'approved_by_signature', 'date' => 'approved_by_approved_at'],
    'Approved by QC' => ['column' => 'qc_approved_by', 'signature' => 'qc_signature', 'date' => 'qc_approved_at'],
    'Approved by QC Buyer' => ['column' => 'qc_buyer_approved_by', 'signature' => 'qc_buyer_signature', 'date' => 'qc_buyer_approved_at']
];

$approval_mapping = $column_mapping[$jabatan] ?? null;

if (!$approval_mapping) {
    die("Error: Invalid jabatan");
}

// Handle edit signature
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_signature'])) {
    $color_approval_id = intval($_POST['color_approval_id']);
    $new_signature_data = $_POST['new_signature_data'] ?? '';
    
    // Check edit count
    $edit_count_stmt = $conn->prepare("
        SELECT COUNT(*) as edit_count 
        FROM approval_history_surabaya 
        WHERE approved_by = ? AND notes LIKE '%EDIT%'
    ");
    $edit_count_stmt->bind_param("i", $approval_id);
    $edit_count_stmt->execute();
    $edit_count = $edit_count_stmt->get_result()->fetch_assoc()['edit_count'];
    $edit_count_stmt->close();
    
    if ($edit_count >= 1) {
        $message = 'Anda sudah menggunakan kesempatan edit tanda tangan!';
        $message_type = 'error';
    } elseif (empty($new_signature_data)) {
        $message = 'Tanda tangan baru tidak boleh kosong!';
        $message_type = 'error';
    } else {
        // Update signature
        $update_sql = "UPDATE color_approvals_surabaya SET 
            {$approval_mapping['signature']} = ?,
            {$approval_mapping['date']} = NOW(),
            updated_at = NOW()
            WHERE id = ?";
        
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("si", $new_signature_data, $color_approval_id);
        
        if ($update_stmt->execute()) {
            // Add to history with EDIT note
            $history_stmt = $conn->prepare("INSERT INTO approval_history_surabaya 
                (color_approval_id, approval_type, approved_by, signature, approved_at, notes) 
                VALUES (?, ?, ?, ?, NOW(), ?)");
            
            $notes = "EDIT - Tanda tangan diubah (kesempatan terpakai)";
            $history_stmt->bind_param("isiss", $color_approval_id, $jabatan, $approval_id, $new_signature_data, $notes);
            $history_stmt->execute();
            $history_stmt->close();
            
            $message = 'Tanda tangan berhasil diubah! Kesempatan edit sudah terpakai.';
            $message_type = 'success';
            
            // Log activity
            create_audit_log($conn, 'Signature Edited', $approval_id, 'approval', "Edited signature for color approval ID: $color_approval_id");
        } else {
            $message = 'Gagal mengubah tanda tangan. Silakan coba lagi.';
            $message_type = 'error';
        }
        
        $update_stmt->close();
    }
}

// Get history of signed components by this user
$history_sql = "
    SELECT 
        ca.id as approval_id,
        ca.color_id,
        ca.component_id,
        mcp.code_color,
        mcp.deskripsi,
        mcp.lemari,
        b.nama_buyer,
        c.nama_collection_surabaya,
        cc.component_name,
        csi.kode_barang,
        csi.keterangan,
        ca.{$approval_mapping['signature']} as my_signature,
        ca.{$approval_mapping['date']} as my_signature_date,
        ca.ka_unit_signature,
        ca.ka_unit_approved_by,
        ca.ka_unit_approved_at,
        ca.color_room_signature,
        ca.color_room_approved_by,
        ca.color_room_approved_at,
        ca.akzonobel_signature,
        ca.akzonobel_approved_by,
        ca.akzonobel_approved_at,
        ca.approved_by_signature,
        ca.approved_by_approved_by,
        ca.approved_by_approved_at,
        ca.qc_signature,
        ca.qc_approved_by,
        ca.qc_approved_at,
        ca.qc_buyer_signature,
        ca.qc_buyer_approved_by,
        ca.qc_buyer_approved_at,
        ca.status_approval
    FROM color_approvals_surabaya ca
    INNER JOIN master_color_panel_surabaya mcp ON ca.color_id = mcp.id
    INNER JOIN buyers_surabaya b ON mcp.buyer_id = b.id
    INNER JOIN collection_surabayas c ON mcp.collection_surabaya_id = c.id
    INNER JOIN color_components_surabaya cc ON ca.component_id = cc.id
    INNER JOIN color_stock_items_surabaya csi ON ca.stock_item_id = csi.id
    WHERE ca.{$approval_mapping['column']} = ?
    ORDER BY ca.{$approval_mapping['date']} DESC
";

$history_stmt = $conn->prepare($history_sql);
$history_stmt->bind_param("i", $approval_id);
$history_stmt->execute();
$history_result = $history_stmt->get_result();

// Check if user can still edit
$can_edit_stmt = $conn->prepare("
    SELECT COUNT(*) as edit_count 
    FROM approval_history_surabaya 
    WHERE approved_by = ? AND notes LIKE '%EDIT%'
");
$can_edit_stmt->bind_param("i", $approval_id);
$can_edit_stmt->execute();
$edit_used = $can_edit_stmt->get_result()->fetch_assoc()['edit_count'];
$can_edit_stmt->close();
$can_edit = ($edit_used < 1);

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

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-purple-100 via-pink-100 to-purple-200">
    
    <!-- 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-history text-purple-600 mr-2"></i>
                    History Tanda Tangan
                </h2>
                <p class="text-gray-600 mt-1">Riwayat component yang telah Anda tandatangani</p>
            </div>
            <div class="text-right">
                <p class="text-sm text-gray-500">Status Edit</p>
                <?php if ($can_edit): ?>
                <span class="px-3 py-1 bg-green-100 text-green-700 text-sm rounded-full">
                    <i class="fas fa-check-circle"></i> Tersedia (1x)
                </span>
                <?php else: ?>
                <span class="px-3 py-1 bg-red-100 text-red-700 text-sm rounded-full">
                    <i class="fas fa-times-circle"></i> Terpakai
                </span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Messages -->
    <?php if (!empty($message)): ?>
    <div class="mb-6 p-4 rounded-lg <?php echo $message_type == 'success' ? 'bg-green-100 border border-green-400 text-green-700' : 'bg-red-100 border border-red-400 text-red-700'; ?>">
        <div class="flex items-center">
            <i class="fas <?php echo $message_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
            <span><?php echo htmlspecialchars($message); ?></span>
        </div>
    </div>
    <?php endif; ?>

    <!-- History List -->
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-4">
            <h3 class="text-lg font-semibold text-white">
                <i class="fas fa-list-check mr-2"></i>
                Daftar Tanda Tangan Saya (<?php echo $history_result->num_rows; ?> Component)
            </h3>
        </div>

        <?php if ($history_result && $history_result->num_rows > 0): ?>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color Code</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer/collection_surabaya</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Perwakilan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal TTD</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php 
                    $no = 1;
                    while ($row = $history_result->fetch_assoc()): 
                        // Count how many signatures are done
                        $signatures_done = 0;
                        if ($row['ka_unit_approved_by']) $signatures_done++;
                        if ($row['color_room_approved_by']) $signatures_done++;
                        if ($row['akzonobel_approved_by']) $signatures_done++;
                        if ($row['approved_by_approved_by']) $signatures_done++;
                        if ($row['qc_approved_by']) $signatures_done++;
                        if ($row['qc_buyer_approved_by']) $signatures_done++;
                        
                        // Get all approval user names
                        $approval_users_surabaya = [];
                        if ($row['ka_unit_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users_surabaya WHERE id = {$row['ka_unit_approved_by']}");
                            $approval_users_surabaya['ka_unit'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['color_room_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users_surabaya WHERE id = {$row['color_room_approved_by']}");
                            $approval_users_surabaya['color_room'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['akzonobel_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users_surabaya WHERE id = {$row['akzonobel_approved_by']}");
                            $approval_users_surabaya['akzonobel'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['approved_by_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users_surabaya WHERE id = {$row['approved_by_approved_by']}");
                            $approval_users_surabaya['approved_by'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['qc_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users_surabaya WHERE id = {$row['qc_approved_by']}");
                            $approval_users_surabaya['qc'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['qc_buyer_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users_surabaya WHERE id = {$row['qc_buyer_approved_by']}");
                            $approval_users_surabaya['qc_buyer'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                    ?>
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo $no++; ?></td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="font-semibold text-gray-900"><?php echo htmlspecialchars($row['code_color']); ?></div>
                            <div class="text-sm text-gray-500"><?php echo htmlspecialchars($row['deskripsi']); ?></div>
                            <div class="text-xs text-gray-400">Lemari: <?php echo htmlspecialchars($row['lemari']); ?></div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 bg-blue-100 text-blue-800 text-sm font-semibold rounded">
                                <?php echo htmlspecialchars($row['component_name']); ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900"><?php echo htmlspecialchars($row['nama_buyer']); ?></div>
                            <div class="text-xs text-gray-500"><?php echo htmlspecialchars($row['nama_collection_surabaya']); ?></div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-mono text-gray-900"><?php echo htmlspecialchars($row['kode_barang']); ?></div>
                            <div class="text-xs text-gray-500"><?php echo htmlspecialchars($row['keterangan']); ?></div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                            <?php echo date('d M Y', strtotime($row['my_signature_date'])); ?>
                            <div class="text-xs text-gray-500"><?php echo date('H:i', strtotime($row['my_signature_date'])); ?></div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs rounded-full <?php echo $row['status_approval'] == 'completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'; ?>">
                                <?php echo $signatures_done; ?>/6 TTD
                            </span>
                            <?php if ($row['status_approval'] == 'completed'): ?>
                            <div class="text-xs text-green-600 mt-1">
                                <i class="fas fa-check-circle"></i> Lengkap
                            </div>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="flex flex-col gap-1">
                                <!-- View My Signature -->
                                <button onclick="viewSignature('<?php echo htmlspecialchars($row['my_signature']); ?>', '<?php echo htmlspecialchars($row['code_color']); ?>', '<?php echo htmlspecialchars($row['component_name']); ?>', 'TTD Saya')" 
                                        class="inline-flex items-center justify-center px-3 py-1 bg-blue-500 text-white text-xs font-medium rounded hover:bg-blue-600 transition-colors">
                                        <i class="fas fa-eye mr-1"></i>
                                        Lihat TTD Saya
                                </button>
                                
                                <!-- View All Signatures -->
                                <button onclick="viewAllSignatures(<?php echo htmlspecialchars(json_encode($row)); ?>, <?php echo htmlspecialchars(json_encode($approval_users_surabaya)); ?>)" 
                                        class="inline-flex items-center justify-center px-3 py-1 bg-purple-500 text-white text-xs font-medium rounded hover:bg-purple-600 transition-colors">
                                        <i class="fas fa-users mr-1"></i>
                                        Lihat Semua TTD
                                </button>
                                
                                <!-- Edit Button -->
                                <?php if ($can_edit): ?>
                                <button onclick="editSignature(<?php echo $row['approval_id']; ?>, '<?php echo htmlspecialchars($row['code_color']); ?>', '<?php echo htmlspecialchars($row['component_name']); ?>', '<?php echo htmlspecialchars($row['kode_barang']); ?>')" 
                                        class="inline-flex items-center justify-center px-3 py-1 bg-orange-500 text-white text-xs font-medium rounded hover:bg-orange-600 transition-colors">
                                        <i class="fas fa-edit mr-1"></i>
                                        Edit TTD
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="p-12 text-center">
            <i class="fas fa-inbox text-6xl text-gray-400 mb-4"></i>
            <h3 class="text-xl font-semibold text-gray-700 mb-2">Belum Ada History</h3>
            <p class="text-gray-500">Anda belum menandatangani component apapun.</p>
            <a href="tanda_tangan.php" class="mt-4 inline-block px-6 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors">
                <i class="fas fa-signature mr-2"></i>
                Mulai Tanda Tangan
            </a>
        </div>
        <?php endif; ?>
    </div>

</main>

<!-- View Single Signature Modal -->
<div id="viewSignatureModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full">
        <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-4 flex justify-between items-center">
            <h3 class="text-xl font-bold text-white">
                <i class="fas fa-eye mr-2"></i>
                <span id="viewModalTitle">Lihat Tanda Tangan</span>
            </h3>
            <button onclick="closeViewModal()" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        
        <div class="p-6">
            <div class="mb-4 grid grid-cols-2 gap-4">
                <div>
                    <p class="text-sm text-gray-600">Color Code:</p>
                    <p class="font-semibold text-gray-900" id="viewColorCode">-</p>
                </div>
                <div>
                    <p class="text-sm text-gray-600">Component:</p>
                    <p class="font-semibold text-gray-900" id="viewComponentName">-</p>
                </div>
            </div>
            
            <div class="border-2 border-gray-300 rounded-lg p-4 bg-gray-50">
                <img id="signatureImage" src="" alt="Tanda Tangan" class="w-full max-h-64 object-contain">
            </div>
            
            <div class="mt-4 flex justify-end">
                <button onclick="closeViewModal()" 
                        class="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<!-- View All Signatures Modal -->
<div id="viewAllSignaturesModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-xl max-w-6xl w-full max-h-[90vh] overflow-y-auto">
        <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-4 flex justify-between items-center sticky top-0 z-10">
            <h3 class="text-xl font-bold text-white">
                <i class="fas fa-users mr-2"></i>
                Semua Tanda Tangan Approval
            </h3>
            <button onclick="closeAllSignaturesModal()" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        
        <div class="p-6">
            <!-- Header Info -->
            <div class="mb-6 p-4 bg-purple-50 rounded-lg">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <p class="text-sm text-gray-600">Color Code:</p>
                        <p class="font-semibold text-gray-900" id="allColorCode">-</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Component:</p>
                        <p class="font-semibold text-gray-900" id="allComponentName">-</p>
                    </div>
                </div>
            </div>

            <!-- Signatures Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" id="signaturesGrid">
                <!-- Will be populated by JavaScript -->
            </div>
            
            <div class="mt-6 flex justify-end">
                <button onclick="closeAllSignaturesModal()" 
                        class="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Signature Modal -->
<div id="editSignatureModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div class="bg-gradient-to-r from-orange-500 to-orange-600 px-6 py-4 flex justify-between items-center">
            <h3 class="text-xl font-bold text-white">
                <i class="fas fa-edit mr-2"></i>
                Edit Tanda Tangan
            </h3>
            <button onclick="closeEditModal()" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        
        <form method="POST" id="editSignatureForm">
            <div class="p-6">
                <!-- Color Info -->
                <div class="mb-4 p-4 bg-orange-50 rounded-lg">
                    <div class="grid grid-cols-3 gap-4">
                        <div>
                            <p class="text-sm text-gray-600">Color Code:</p>
                            <p class="font-semibold text-gray-900" id="editColorCode">-</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Component:</p>
                            <p class="font-semibold text-gray-900" id="editComponentName">-</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Perwakilan:</p>
                            <p class="font-semibold text-gray-900 text-xs" id="editKodeBarang">-</p>
                        </div>
                    </div>
                </div>

                <!-- Signature Canvas -->
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Tanda Tangan Baru
                    </label>
                    <div class="border-2 border-gray-300 rounded-lg overflow-hidden bg-white">
                        <canvas id="editSignatureCanvas" width="600" height="200" class="w-full cursor-crosshair"></canvas>
                    </div>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle"></i> 
                        Buat tanda tangan baru
                    </p>
                </div>

                <!-- Buttons -->
                <div class="flex space-x-3">
                    <button type="button" onclick="clearEditSignature()" 
                            class="flex-1 px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">
                        <i class="fas fa-eraser mr-2"></i>
                        Hapus
                    </button>
                    <button type="button" onclick="saveEditSignature()" 
                            class="flex-1 px-4 py-2 bg-gradient-to-r from-orange-500 to-orange-600 text-white rounded-lg hover:from-orange-600 hover:to-orange-700 transition-all duration-200">
                        <i class="fas fa-save mr-2"></i>
                        Simpan Perubahan
                    </button>
                </div>

                <!-- Warning -->
                <div class="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                    <p class="text-sm text-red-800">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        <strong>PERHATIAN:</strong> Ini adalah satu-satunya kesempatan Anda untuk mengedit tanda tangan. Setelah ini, Anda tidak bisa mengedit lagi!
                    </p>
                </div>
            </div>

            <input type="hidden" name="color_approval_id" id="editColorApprovalId">
            <input type="hidden" name="new_signature_data" id="newSignatureData">
            <input type="hidden" name="edit_signature" value="1">
        </form>
    </div>
</div>

<script>
// View single signature modal
function viewSignature(signatureData, colorCode, componentName, title) {
    document.getElementById('viewModalTitle').textContent = title;
    document.getElementById('viewColorCode').textContent = colorCode;
    document.getElementById('viewComponentName').textContent = componentName;
    document.getElementById('signatureImage').src = signatureData;
    document.getElementById('viewSignatureModal').classList.remove('hidden');
}

function closeViewModal() {
    document.getElementById('viewSignatureModal').classList.add('hidden');
}

// View all signatures modal
function viewAllSignatures(rowData, approvalUsers) {
    document.getElementById('allColorCode').textContent = rowData.code_color;
    document.getElementById('allComponentName').textContent = rowData.component_name;
    
    const signaturesGrid = document.getElementById('signaturesGrid');
    signaturesGrid.innerHTML = '';
    
    // Array of all approvals
    const approvals = [
        {
            title: 'K A Unit',
            signature: rowData.ka_unit_signature,
            approved_by: rowData.ka_unit_approved_by,
            approved_at: rowData.ka_unit_approved_at,
            user_name: approvalUsers.ka_unit
        },
        {
            title: 'Color Room',
            signature: rowData.color_room_signature,
            approved_by: rowData.color_room_approved_by,
            approved_at: rowData.color_room_approved_at,
            user_name: approvalUsers.color_room
        },
        {
            title: 'Akzonobel',
            signature: rowData.akzonobel_signature,
            approved_by: rowData.akzonobel_approved_by,
            approved_at: rowData.akzonobel_approved_at,
            user_name: approvalUsers.akzonobel
        },
        {
            title: 'Approved by',
            signature: rowData.approved_by_signature,
            approved_by: rowData.approved_by_approved_by,
            approved_at: rowData.approved_by_approved_at,
            user_name: approvalUsers.approved_by
        },
        {
            title: 'Approved by QC',
            signature: rowData.qc_signature,
            approved_by: rowData.qc_approved_by,
            approved_at: rowData.qc_approved_at,
            user_name: approvalUsers.qc
        },
        {
            title: 'Approved by QC Buyer',
            signature: rowData.qc_buyer_signature,
            approved_by: rowData.qc_buyer_approved_by,
            approved_at: rowData.qc_buyer_approved_at,
            user_name: approvalUsers.qc_buyer
        }
    ];
    
    // Generate cards for each approval
    approvals.forEach(function(approval) {
        const card = document.createElement('div');
        
        if (approval.approved_by) {
            // Signed
            card.className = 'border-2 border-green-500 rounded-lg p-4 bg-green-50';
            card.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-semibold text-gray-900">${approval.title}</h4>
                    <i class="fas fa-check-circle text-green-500 text-xl"></i>
                </div>
                <div class="mb-3">
                    <p class="text-xs text-gray-600">Ditandatangani oleh:</p>
                    <p class="text-sm font-semibold text-gray-900">${approval.user_name || 'Unknown'}</p>
                    <p class="text-xs text-gray-500 mt-1">${formatDate(approval.approved_at)}</p>
                </div>
                <div class="border-2 border-gray-300 rounded p-2 bg-white">
                    <img src="${approval.signature}" alt="${approval.title} Signature" class="w-full h-24 object-contain">
                </div>
                <button onclick="viewSignature('${approval.signature}', '${rowData.code_color}', '${rowData.component_name}', '${approval.title}')" 
                        class="mt-2 w-full px-3 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600 transition-colors">
                    <i class="fas fa-expand mr-1"></i> Perbesar
                </button>
            `;
        } else {
            // Not signed yet
            card.className = 'border-2 border-gray-300 rounded-lg p-4 bg-gray-50';
            card.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-semibold text-gray-700">${approval.title}</h4>
                    <i class="fas fa-circle text-gray-400 text-xl"></i>
                </div>
                <div class="flex items-center justify-center h-32 border-2 border-dashed border-gray-300 rounded bg-white">
                    <div class="text-center">
                        <i class="fas fa-hourglass-half text-gray-400 text-3xl mb-2"></i>
                        <p class="text-sm text-gray-500">Belum TTD</p>
                    </div>
                </div>
            `;
        }
        
        signaturesGrid.appendChild(card);
    });
    
    document.getElementById('viewAllSignaturesModal').classList.remove('hidden');
}

function closeAllSignaturesModal() {
    document.getElementById('viewAllSignaturesModal').classList.add('hidden');
}

function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
    return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}, ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}

// Edit signature canvas setup
let editCanvas, editCtx;
let isEditDrawing = false;
let editLastX = 0;
let editLastY = 0;

document.addEventListener('DOMContentLoaded', function() {
    editCanvas = document.getElementById('editSignatureCanvas');
    editCtx = editCanvas.getContext('2d');
    
    // Set canvas background to white
    editCtx.fillStyle = 'white';
    editCtx.fillRect(0, 0, editCanvas.width, editCanvas.height);
    
    // Set drawing styles
    editCtx.strokeStyle = '#000000';
    editCtx.lineWidth = 2;
    editCtx.lineCap = 'round';
    editCtx.lineJoin = 'round';
    
    // Mouse events
    editCanvas.addEventListener('mousedown', startEditDrawing);
    editCanvas.addEventListener('mousemove', drawEdit);
    editCanvas.addEventListener('mouseup', stopEditDrawing);
    editCanvas.addEventListener('mouseout', stopEditDrawing);
    
    // Touch events
    editCanvas.addEventListener('touchstart', handleEditTouchStart);
    editCanvas.addEventListener('touchmove', handleEditTouchMove);
    editCanvas.addEventListener('touchend', stopEditDrawing);
});

function startEditDrawing(e) {
    isEditDrawing = true;
    const rect = editCanvas.getBoundingClientRect();
    editLastX = e.clientX - rect.left;
    editLastY = e.clientY - rect.top;
}

function drawEdit(e) {
    if (!isEditDrawing) return;
    
    const rect = editCanvas.getBoundingClientRect();
    const currentX = e.clientX - rect.left;
    const currentY = e.clientY - rect.top;
    
    editCtx.beginPath();
    editCtx.moveTo(editLastX, editLastY);
    editCtx.lineTo(currentX, currentY);
    editCtx.stroke();
    
    editLastX = currentX;
    editLastY = currentY;
}

function stopEditDrawing() {
    isEditDrawing = false;
}

function handleEditTouchStart(e) {
    e.preventDefault();
    const touch = e.touches[0];
    const rect = editCanvas.getBoundingClientRect();
    isEditDrawing = true;
    editLastX = touch.clientX - rect.left;
    editLastY = touch.clientY - rect.top;
}

function handleEditTouchMove(e) {
    if (!isEditDrawing) return;
    e.preventDefault();
    
    const touch = e.touches[0];
    const rect = editCanvas.getBoundingClientRect();
    const currentX = touch.clientX - rect.left;
    const currentY = touch.clientY - rect.top;
    
    editCtx.beginPath();
    editCtx.moveTo(editLastX, editLastY);
    editCtx.lineTo(currentX, currentY);
    editCtx.stroke();
    
    editLastX = currentX;
    editLastY = currentY;
}

function clearEditSignature() {
    editCtx.fillStyle = 'white';
    editCtx.fillRect(0, 0, editCanvas.width, editCanvas.height);
}

function editSignature(approvalId, colorCode, componentName, kodeBarang) {
    document.getElementById('editColorApprovalId').value = approvalId;
    document.getElementById('editColorCode').textContent = colorCode;
    document.getElementById('editComponentName').textContent = componentName;
    document.getElementById('editKodeBarang').textContent = kodeBarang;
    document.getElementById('editSignatureModal').classList.remove('hidden');
    clearEditSignature();
}

function closeEditModal() {
    document.getElementById('editSignatureModal').classList.add('hidden');
    clearEditSignature();
}

function saveEditSignature() {
    // Check if canvas is empty
    const imageData = editCtx.getImageData(0, 0, editCanvas.width, editCanvas.height);
    const pixels = imageData.data;
    let isEmpty = true;
    
    for (let i = 0; i < pixels.length; i += 4) {
        if (pixels[i] !== 255 || pixels[i + 1] !== 255 || pixels[i + 2] !== 255) {
            isEmpty = false;
            break;
        }
    }
    
    if (isEmpty) {
        alert('Tanda tangan baru tidak boleh kosong!');
        return;
    }
    
    // Convert canvas to base64
    const signatureData = editCanvas.toDataURL('image/png');
    document.getElementById('newSignatureData').value = signatureData;
    
    // Submit form with strong confirmation
    if (confirm('PERHATIAN!\n\nIni adalah satu-satunya kesempatan Anda untuk mengedit tanda tangan.\nSetelah ini, Anda TIDAK BISA mengedit lagi!\n\nApakah Anda yakin ingin menyimpan perubahan ini?')) {
        if (confirm('Konfirmasi sekali lagi:\nApakah tanda tangan baru sudah benar dan Anda yakin ingin menyimpannya?')) {
            document.getElementById('editSignatureForm').submit();
        }
    }
}

// Close modals when clicking outside
document.getElementById('viewSignatureModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeViewModal();
    }
});

document.getElementById('viewAllSignaturesModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeAllSignaturesModal();
    }
});

document.getElementById('editSignatureModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeEditModal();
    }
});
</script>

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