<?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 
        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 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 
                (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 filter parameters
$filter_buyer = isset($_GET['buyer']) ? intval($_GET['buyer']) : 0;
$filter_component = isset($_GET['component']) ? intval($_GET['component']) : 0;

// Get list of buyers for filter dropdown
$buyers_sql = "
    SELECT DISTINCT b.id, b.nama_buyer 
    FROM color_approvals ca
    INNER JOIN master_color_panel mcp ON ca.color_id = mcp.id
    INNER JOIN buyers b ON mcp.buyer_id = b.id
    WHERE ca.{$approval_mapping['column']} = ?
    ORDER BY b.nama_buyer ASC
";
$buyers_stmt = $conn->prepare($buyers_sql);
$buyers_stmt->bind_param("i", $approval_id);
$buyers_stmt->execute();
$buyers_result = $buyers_stmt->get_result();

// Get list of components for filter dropdown
$components_sql = "
    SELECT DISTINCT cc.id, cc.component_name 
    FROM color_approvals ca
    INNER JOIN color_components cc ON ca.component_id = cc.id
    WHERE ca.{$approval_mapping['column']} = ?
    ORDER BY cc.component_name ASC
";
$components_stmt = $conn->prepare($components_sql);
$components_stmt->bind_param("i", $approval_id);
$components_stmt->execute();
$components_result = $components_stmt->get_result();

// Build WHERE clause for filters
$where_conditions = ["ca.{$approval_mapping['column']} = ?"];
$params = [$approval_id];
$param_types = "i";

if ($filter_buyer > 0) {
    $where_conditions[] = "mcp.buyer_id = ?";
    $params[] = $filter_buyer;
    $param_types .= "i";
}

if ($filter_component > 0) {
    $where_conditions[] = "ca.component_id = ?";
    $params[] = $filter_component;
    $param_types .= "i";
}

$where_clause = implode(" AND ", $where_conditions);

// Get history of signed components by this user with filters
$history_sql = "
    SELECT 
        ca.id as approval_id,
        ca.color_id,
        ca.component_id,
        mcp.code_color,
        mcp.deskripsi,
        mcp.lemari,
        b.id as buyer_id,
        b.nama_buyer,
        c.nama_collection,
        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 ca
    INNER JOIN master_color_panel mcp ON ca.color_id = mcp.id
    INNER JOIN buyers b ON mcp.buyer_id = b.id
    INNER JOIN collections c ON mcp.collection_id = c.id
    INNER JOIN color_components cc ON ca.component_id = cc.id
    INNER JOIN color_stock_items csi ON ca.stock_item_id = csi.id
    WHERE $where_clause
    ORDER BY ca.{$approval_mapping['date']} DESC
";

$history_stmt = $conn->prepare($history_sql);
$history_stmt->bind_param($param_types, ...$params);
$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 
    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';
?>

<style>
/* Mobile Responsive Styles */
@media (max-width: 768px) {
    .mobile-card {
        display: block !important;
    }
    
    .desktop-table {
        display: none !important;
    }
    
    .mobile-card-item {
        background: white;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 12px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        border-left: 4px solid #9333ea;
    }
    
    .mobile-card-header {
        border-bottom: 1px solid #e5e7eb;
        padding-bottom: 12px;
        margin-bottom: 12px;
    }
    
    .mobile-card-body {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }
    
    .mobile-info-row {
        display: flex;
        justify-content: space-between;
        align-items: start;
        padding: 6px 0;
    }
    
    .mobile-info-label {
        font-size: 12px;
        color: #6b7280;
        font-weight: 500;
        flex-shrink: 0;
        width: 90px;
    }
    
    .mobile-info-value {
        font-size: 13px;
        color: #111827;
        font-weight: 600;
        text-align: right;
        flex: 1;
    }
    
    .mobile-actions {
        display: flex;
        flex-direction: column;
        gap: 8px;
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px solid #e5e7eb;
    }
    
    .mobile-actions button {
        width: 100%;
        padding: 10px 16px;
        font-size: 13px;
    }
}

@media (min-width: 769px) {
    .mobile-card {
        display: none !important;
    }
    
    .desktop-table {
        display: table !important;
    }
}

/* Modal responsive adjustments */
@media (max-width: 640px) {
    .modal-container {
        margin: 10px;
        max-height: calc(100vh - 20px);
    }
    
    .signatures-grid-responsive {
        grid-template-columns: 1fr !important;
    }
    
    #editSignatureCanvas {
        height: 150px;
    }
}

/* Filter Styles */
.filter-section {
    background: white;
    border-radius: 12px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.filter-select {
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
    background-position: right 0.5rem center;
    background-repeat: no-repeat;
    background-size: 1.5em 1.5em;
    padding-right: 2.5rem;
}

.filter-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    background: #ddd6fe;
    color: #6b21a8;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 600;
}

.filter-badge button {
    background: none;
    border: none;
    color: #6b21a8;
    cursor: pointer;
    padding: 0;
    margin: 0;
    font-size: 16px;
    line-height: 1;
}

.filter-badge button:hover {
    color: #581c87;
}
</style>

<!-- Main Content Area -->
<main class="flex-1 p-3 sm: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-4 sm:p-6 mb-4 sm:mb-6">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div>
                <h2 class="text-xl sm: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-sm sm:text-base text-gray-600 mt-1">Riwayat component yang telah Anda tandatangani</p>
            </div>
            <div class="w-full sm:w-auto text-left sm:text-right">
                <p class="text-xs sm:text-sm text-gray-500">Status Edit</p>
                <?php if ($can_edit): ?>
                <span class="inline-block px-3 py-1 bg-green-100 text-green-700 text-xs sm:text-sm rounded-full mt-1">
                    <i class="fas fa-check-circle"></i> Tersedia (1x)
                </span>
                <?php else: ?>
                <span class="inline-block px-3 py-1 bg-red-100 text-red-700 text-xs sm:text-sm rounded-full mt-1">
                    <i class="fas fa-times-circle"></i> Terpakai
                </span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Messages -->
    <?php if (!empty($message)): ?>
    <div class="mb-4 sm:mb-6 p-3 sm: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 text-sm sm:text-base">
            <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; ?>

    <!-- Filter Section -->
    <div class="filter-section mb-4 sm:mb-6">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-4">
            <div class="flex items-center gap-2">
                <i class="fas fa-filter text-purple-600"></i>
                <h3 class="text-base sm:text-lg font-semibold text-gray-800">Filter Data</h3>
            </div>
            <?php if ($filter_buyer > 0 || $filter_component > 0): ?>
            <a href="history_tanda_tangan.php" class="text-sm text-red-600 hover:text-red-700 font-medium">
                <i class="fas fa-times-circle mr-1"></i>
                Reset Filter
            </a>
            <?php endif; ?>
        </div>

        <form method="GET" action="" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
            <!-- Buyer Filter -->
            <div>
                <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-building mr-1"></i>
                    Buyer
                </label>
                <select name="buyer" class="filter-select w-full px-3 sm:px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm sm:text-base" onchange="this.form.submit()">
                    <option value="0">Semua Buyer</option>
                    <?php 
                    $buyers_result->data_seek(0);
                    while ($buyer = $buyers_result->fetch_assoc()): 
                    ?>
                    <option value="<?php echo $buyer['id']; ?>" <?php echo $filter_buyer == $buyer['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($buyer['nama_buyer']); ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <!-- Component Filter -->
            <div>
                <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-puzzle-piece mr-1"></i>
                    Component
                </label>
                <select name="component" class="filter-select w-full px-3 sm:px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm sm:text-base" onchange="this.form.submit()">
                    <option value="0">Semua Component</option>
                    <?php 
                    $components_result->data_seek(0);
                    while ($component = $components_result->fetch_assoc()): 
                    ?>
                    <option value="<?php echo $component['id']; ?>" <?php echo $filter_component == $component['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($component['component_name']); ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <!-- Apply Button (Mobile) -->
            <div class="sm:hidden">
                <label class="block text-xs font-medium text-gray-700 mb-2 opacity-0">Action</label>
                <button type="submit" class="w-full px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors text-sm font-medium">
                    <i class="fas fa-search mr-2"></i>
                    Terapkan Filter
                </button>
            </div>
        </form>

        <!-- Active Filters Display -->
        <?php if ($filter_buyer > 0 || $filter_component > 0): ?>
        <div class="mt-4 pt-4 border-t border-gray-200">
            <p class="text-xs sm:text-sm text-gray-600 mb-2">Filter Aktif:</p>
            <div class="flex flex-wrap gap-2">
                <?php if ($filter_buyer > 0): 
                    $buyer_name_stmt = $conn->query("SELECT nama_buyer FROM buyers WHERE id = $filter_buyer");
                    $buyer_name = $buyer_name_stmt->fetch_assoc()['nama_buyer'];
                ?>
                <span class="filter-badge">
                    <i class="fas fa-building"></i>
                    <?php echo htmlspecialchars($buyer_name); ?>
                    <a href="?component=<?php echo $filter_component; ?>">
                        <button type="button" title="Hapus filter">×</button>
                    </a>
                </span>
                <?php endif; ?>

                <?php if ($filter_component > 0): 
                    $component_name_stmt = $conn->query("SELECT component_name FROM color_components WHERE id = $filter_component");
                    $component_name = $component_name_stmt->fetch_assoc()['component_name'];
                ?>
                <span class="filter-badge">
                    <i class="fas fa-puzzle-piece"></i>
                    <?php echo htmlspecialchars($component_name); ?>
                    <a href="?buyer=<?php echo $filter_buyer; ?>">
                        <button type="button" title="Hapus filter">×</button>
                    </a>
                </span>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- 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-4 sm:px-6 py-3 sm:py-4">
            <h3 class="text-base sm: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): ?>
        
        <!-- Desktop Table View -->
        <div class="desktop-table 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</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;
                    $history_result->data_seek(0);
                    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 = [];
                        if ($row['ka_unit_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['ka_unit_approved_by']}");
                            $approval_users['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 WHERE id = {$row['color_room_approved_by']}");
                            $approval_users['color_room'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['akzonobel_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['akzonobel_approved_by']}");
                            $approval_users['akzonobel'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['approved_by_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['approved_by_approved_by']}");
                            $approval_users['approved_by'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['qc_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['qc_approved_by']}");
                            $approval_users['qc'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                        }
                        if ($row['qc_buyer_approved_by']) {
                            $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['qc_buyer_approved_by']}");
                            $approval_users['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']); ?></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">
                                <button onclick='viewSignature(<?php echo json_encode($row['my_signature']); ?>, <?php echo json_encode($row['code_color']); ?>, <?php echo json_encode($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>
                                <button onclick='viewAllSignatures(<?php echo json_encode($row); ?>, <?php echo json_encode($approval_users); ?>)' 
                                        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>
                                <?php if ($can_edit): ?>
                                <button onclick='editSignature(<?php echo $row['approval_id']; ?>, <?php echo json_encode($row['code_color']); ?>, <?php echo json_encode($row['component_name']); ?>, <?php echo json_encode($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>

        <!-- Mobile Card View -->
        <div class="mobile-card p-3">
            <?php 
            $no = 1;
            $history_result->data_seek(0);
            while ($row = $history_result->fetch_assoc()): 
                // Count signatures
                $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 approval users
                $approval_users = [];
                if ($row['ka_unit_approved_by']) {
                    $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['ka_unit_approved_by']}");
                    $approval_users['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 WHERE id = {$row['color_room_approved_by']}");
                    $approval_users['color_room'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                }
                if ($row['akzonobel_approved_by']) {
                    $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['akzonobel_approved_by']}");
                    $approval_users['akzonobel'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                }
                if ($row['approved_by_approved_by']) {
                    $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['approved_by_approved_by']}");
                    $approval_users['approved_by'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                }
                if ($row['qc_approved_by']) {
                    $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['qc_approved_by']}");
                    $approval_users['qc'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                }
                if ($row['qc_buyer_approved_by']) {
                    $user_stmt = $conn->query("SELECT nama_lengkap FROM approval_users WHERE id = {$row['qc_buyer_approved_by']}");
                    $approval_users['qc_buyer'] = $user_stmt->fetch_assoc()['nama_lengkap'] ?? 'Unknown';
                }
            ?>
            <div class="mobile-card-item">
                <div class="mobile-card-header">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-xs font-semibold text-purple-600">#<?php echo $no++; ?></span>
                        <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>
                    </div>
                    <h4 class="font-bold text-gray-900 text-sm"><?php echo htmlspecialchars($row['code_color']); ?></h4>
                    <p class="text-xs text-gray-600 mt-1"><?php echo htmlspecialchars($row['deskripsi']); ?></p>
                </div>
                
                <div class="mobile-card-body">
                    <div class="mobile-info-row">
                        <span class="mobile-info-label">Component:</span>
                        <span class="mobile-info-value">
                            <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">
                                <?php echo htmlspecialchars($row['component_name']); ?>
                            </span>
                        </span>
                    </div>
                    
                    <div class="mobile-info-row">
                        <span class="mobile-info-label">Buyer:</span>
                        <span class="mobile-info-value"><?php echo htmlspecialchars($row['nama_buyer']); ?></span>
                    </div>
                    
                    <div class="mobile-info-row">
                        <span class="mobile-info-label">Collection:</span>
                        <span class="mobile-info-value text-xs"><?php echo htmlspecialchars($row['nama_collection']); ?></span>
                    </div>
                    
                    <div class="mobile-info-row">
                        <span class="mobile-info-label">Perwakilan:</span>
                        <span class="mobile-info-value font-mono text-xs"><?php echo htmlspecialchars($row['kode_barang']); ?></span>
                    </div>
                    
                    <div class="mobile-info-row">
                        <span class="mobile-info-label">Lemari:</span>
                        <span class="mobile-info-value"><?php echo htmlspecialchars($row['lemari']); ?></span>
                    </div>
                    
                    <div class="mobile-info-row">
                        <span class="mobile-info-label">Tanggal TTD:</span>
                        <span class="mobile-info-value text-xs">
                            <?php echo date('d M Y, H:i', strtotime($row['my_signature_date'])); ?>
                        </span>
                    </div>
                </div>
                
                <div class="mobile-actions">
                    <button onclick='viewSignature(<?php echo json_encode($row['my_signature']); ?>, <?php echo json_encode($row['code_color']); ?>, <?php echo json_encode($row['component_name']); ?>, "TTD Saya")' 
                            class="bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
                            <i class="fas fa-eye mr-1"></i> Lihat TTD Saya
                    </button>
                    <button onclick='viewAllSignatures(<?php echo json_encode($row); ?>, <?php echo json_encode($approval_users); ?>)' 
                            class="bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors">
                            <i class="fas fa-users mr-1"></i> Lihat Semua TTD
                    </button>
                    <?php if ($can_edit): ?>
                    <button onclick='editSignature(<?php echo $row['approval_id']; ?>, <?php echo json_encode($row['code_color']); ?>, <?php echo json_encode($row['component_name']); ?>, <?php echo json_encode($row['kode_barang']); ?>)' 
                            class="bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors">
                            <i class="fas fa-edit mr-1"></i> Edit TTD
                    </button>
                    <?php endif; ?>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        
        <?php else: ?>
        <div class="p-8 sm:p-12 text-center">
            <i class="fas fa-inbox text-5xl sm:text-6xl text-gray-400 mb-4"></i>
            <h3 class="text-lg sm:text-xl font-semibold text-gray-700 mb-2">
                <?php if ($filter_buyer > 0 || $filter_component > 0): ?>
                    Tidak Ada Data dengan Filter Ini
                <?php else: ?>
                    Belum Ada History
                <?php endif; ?>
            </h3>
            <p class="text-sm sm:text-base text-gray-500">
                <?php if ($filter_buyer > 0 || $filter_component > 0): ?>
                    Coba ubah atau reset filter untuk melihat data lainnya.
                <?php else: ?>
                    Anda belum menandatangani component apapun.
                <?php endif; ?>
            </p>
            <?php if ($filter_buyer > 0 || $filter_component > 0): ?>
            <a href="history_tanda_tangan.php" class="mt-4 inline-block px-4 sm:px-6 py-2 bg-purple-500 text-white text-sm sm:text-base rounded-lg hover:bg-purple-600 transition-colors">
                <i class="fas fa-redo mr-2"></i>
                Reset Filter
            </a>
            <?php else: ?>
            <a href="tanda_tangan.php" class="mt-4 inline-block px-4 sm:px-6 py-2 bg-purple-500 text-white text-sm sm:text-base rounded-lg hover:bg-purple-600 transition-colors">
                <i class="fas fa-signature mr-2"></i>
                Mulai Tanda Tangan
            </a>
            <?php endif; ?>
        </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 w-full modal-container" style="max-width: 600px;">
        <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-4 sm:px-6 py-3 sm:py-4 flex justify-between items-center rounded-t-lg">
            <h3 class="text-lg sm: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-xl sm:text-2xl"></i>
            </button>
        </div>
        
        <div class="p-4 sm:p-6">
            <div class="mb-4 grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                <div>
                    <p class="text-xs sm:text-sm text-gray-600">Color Code:</p>
                    <p class="font-semibold text-sm sm:text-base text-gray-900" id="viewColorCode">-</p>
                </div>
                <div>
                    <p class="text-xs sm:text-sm text-gray-600">Component:</p>
                    <p class="font-semibold text-sm sm:text-base text-gray-900" id="viewComponentName">-</p>
                </div>
            </div>
            
            <div class="border-2 border-gray-300 rounded-lg p-3 sm:p-4 bg-gray-50">
                <img id="signatureImage" src="" alt="Tanda Tangan" class="w-full max-h-48 sm:max-h-64 object-contain">
            </div>
            
            <div class="mt-4 flex justify-end">
                <button onclick="closeViewModal()" 
                        class="px-4 sm:px-6 py-2 bg-gray-500 text-white text-sm sm:text-base 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 w-full modal-container max-w-6xl max-h-[90vh] overflow-y-auto">
        <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-4 sm:px-6 py-3 sm:py-4 flex justify-between items-center sticky top-0 z-10 rounded-t-lg">
            <h3 class="text-base sm: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-xl sm:text-2xl"></i>
            </button>
        </div>
        
        <div class="p-4 sm:p-6">
            <!-- Header Info -->
            <div class="mb-4 sm:mb-6 p-3 sm:p-4 bg-purple-50 rounded-lg">
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                    <div>
                        <p class="text-xs sm:text-sm text-gray-600">Color Code:</p>
                        <p class="font-semibold text-sm sm:text-base text-gray-900" id="allColorCode">-</p>
                    </div>
                    <div>
                        <p class="text-xs sm:text-sm text-gray-600">Component:</p>
                        <p class="font-semibold text-sm sm:text-base text-gray-900" id="allComponentName">-</p>
                    </div>
                </div>
            </div>

            <!-- Signatures Grid -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4 signatures-grid-responsive" id="signaturesGrid">
                <!-- Will be populated by JavaScript -->
            </div>
            
            <div class="mt-4 sm:mt-6 flex justify-end">
                <button onclick="closeAllSignaturesModal()" 
                        class="px-4 sm:px-6 py-2 bg-gray-500 text-white text-sm sm:text-base 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 w-full modal-container max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="bg-gradient-to-r from-orange-500 to-orange-600 px-4 sm:px-6 py-3 sm:py-4 flex justify-between items-center rounded-t-lg">
            <h3 class="text-base sm: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-xl sm:text-2xl"></i>
            </button>
        </div>
        
        <form method="POST" id="editSignatureForm">
            <div class="p-4 sm:p-6">
                <!-- Color Info -->
                <div class="mb-4 p-3 sm:p-4 bg-orange-50 rounded-lg">
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
                        <div>
                            <p class="text-xs sm:text-sm text-gray-600">Color Code:</p>
                            <p class="font-semibold text-sm text-gray-900" id="editColorCode">-</p>
                        </div>
                        <div>
                            <p class="text-xs sm:text-sm text-gray-600">Component:</p>
                            <p class="font-semibold text-sm text-gray-900" id="editComponentName">-</p>
                        </div>
                        <div>
                            <p class="text-xs sm: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-xs sm: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 touch-none"></canvas>
                    </div>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle"></i> 
                        Buat tanda tangan baru dengan mouse atau sentuhan
                    </p>
                </div>

                <!-- Buttons -->
                <div class="flex flex-col sm:flex-row gap-2 sm:gap-3">
                    <button type="button" onclick="clearEditSignature()" 
                            class="w-full sm:flex-1 px-4 py-2 bg-gray-200 text-gray-700 text-sm sm:text-base rounded-lg hover:bg-gray-300 transition-colors">
                        <i class="fas fa-eraser mr-2"></i>
                        Hapus
                    </button>
                    <button type="button" onclick="saveEditSignature()" 
                            class="w-full sm:flex-1 px-4 py-2 bg-gradient-to-r from-orange-500 to-orange-600 text-white text-sm sm:text-base 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-xs sm: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-3 sm:p-4 bg-green-50';
            card.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-semibold text-sm text-gray-900">${approval.title}</h4>
                    <i class="fas fa-check-circle text-green-500 text-lg sm:text-xl"></i>
                </div>
                <div class="mb-3">
                    <p class="text-xs text-gray-600">Ditandatangani oleh:</p>
                    <p class="text-xs sm: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-20 sm: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-3 sm:p-4 bg-gray-50';
            card.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-semibold text-sm text-gray-700">${approval.title}</h4>
                    <i class="fas fa-circle text-gray-400 text-lg sm:text-xl"></i>
                </div>
                <div class="flex items-center justify-center h-24 sm: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-2xl sm:text-3xl mb-2"></i>
                        <p class="text-xs sm: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 for mobile
    editCanvas.addEventListener('touchstart', handleEditTouchStart, {passive: false});
    editCanvas.addEventListener('touchmove', handleEditTouchMove, {passive: false});
    editCanvas.addEventListener('touchend', stopEditDrawing);
});

function startEditDrawing(e) {
    isEditDrawing = true;
    const rect = editCanvas.getBoundingClientRect();
    const scaleX = editCanvas.width / rect.width;
    const scaleY = editCanvas.height / rect.height;
    editLastX = (e.clientX - rect.left) * scaleX;
    editLastY = (e.clientY - rect.top) * scaleY;
}

function drawEdit(e) {
    if (!isEditDrawing) return;
    
    const rect = editCanvas.getBoundingClientRect();
    const scaleX = editCanvas.width / rect.width;
    const scaleY = editCanvas.height / rect.height;
    const currentX = (e.clientX - rect.left) * scaleX;
    const currentY = (e.clientY - rect.top) * scaleY;
    
    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();
    const scaleX = editCanvas.width / rect.width;
    const scaleY = editCanvas.height / rect.height;
    isEditDrawing = true;
    editLastX = (touch.clientX - rect.left) * scaleX;
    editLastY = (touch.clientY - rect.top) * scaleY;
}

function handleEditTouchMove(e) {
    if (!isEditDrawing) return;
    e.preventDefault();
    
    const touch = e.touches[0];
    const rect = editCanvas.getBoundingClientRect();
    const scaleX = editCanvas.width / rect.width;
    const scaleY = editCanvas.height / rect.height;
    const currentX = (touch.clientX - rect.left) * scaleX;
    const currentY = (touch.clientY - rect.top) * scaleY;
    
    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'; ?>