<?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 = "Tanda Tangan Color Code";

// 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 signature submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_signature'])) {
    $color_id = intval($_POST['color_id']);
    $component_id = intval($_POST['component_id']);
    $stock_item_id = intval($_POST['stock_item_id']);
    $signature_data = $_POST['signature_data'] ?? '';
    
    if (empty($signature_data)) {
        $message = 'Tanda tangan tidak boleh kosong!';
        $message_type = 'error';
    } else {
        // Check if color_approval record exists for this color + component
        $check_stmt = $conn->prepare("SELECT id, {$approval_mapping['column']} FROM color_approvals WHERE color_id = ? AND component_id = ?");
        $check_stmt->bind_param("ii", $color_id, $component_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows == 0) {
            // Create new color_approval record for this color + component
            $create_stmt = $conn->prepare("INSERT INTO color_approvals (color_id, component_id, stock_item_id, status_approval) VALUES (?, ?, ?, 'pending')");
            $create_stmt->bind_param("iii", $color_id, $component_id, $stock_item_id);
            $create_stmt->execute();
            $color_approval_id = $conn->insert_id;
            $create_stmt->close();
        } else {
            $approval_record = $check_result->fetch_assoc();
            $color_approval_id = $approval_record['id'];
            
            // Check if already signed by this user
            if ($approval_record[$approval_mapping['column']] != null) {
                $message = 'Anda sudah menandatangani component ini!';
                $message_type = 'error';
                $check_stmt->close();
                goto skip_save;
            }
        }
        $check_stmt->close();
        
        // Save signature for this component
        $update_sql = "UPDATE color_approvals SET 
            {$approval_mapping['signature']} = ?,
            {$approval_mapping['column']} = ?,
            {$approval_mapping['date']} = NOW(),
            updated_at = NOW()
            WHERE id = ?";
        
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("sii", $signature_data, $approval_id, $color_approval_id);
        
        if ($update_stmt->execute()) {
            // Add to history
            $history_stmt = $conn->prepare("INSERT INTO approval_history 
                (color_approval_id, approval_type, approved_by, signature, approved_at, notes) 
                VALUES (?, ?, ?, ?, NOW(), ?)");
            
            $notes = "Tanda tangan untuk Component";
            $history_stmt->bind_param("isiss", $color_approval_id, $jabatan, $approval_id, $signature_data, $notes);
            $history_stmt->execute();
            $history_stmt->close();
            
            // Check if all approvals are complete (6/6)
            $check_complete = $conn->query("
                SELECT 
                    ka_unit_approved_by,
                    color_room_approved_by,
                    akzonobel_approved_by,
                    approved_by_approved_by,
                    qc_approved_by,
                    qc_buyer_approved_by
                FROM color_approvals 
                WHERE id = $color_approval_id
            ")->fetch_assoc();
            
            $all_signed = true;
            foreach ($check_complete as $col_value) {
                if ($col_value === null) {
                    $all_signed = false;
                    break;
                }
            }
            
            if ($all_signed) {
                // Update status to completed
                $conn->query("UPDATE color_approvals SET status_approval = 'completed' WHERE id = $color_approval_id");
                
                // Copy signatures to ALL stock items in this component
                $copy_query = "
                    SELECT id FROM color_stock_items 
                    WHERE color_id = $color_id 
                    AND component_id = $component_id
                ";
                $copy_result = $conn->query($copy_query);
                
                $message = 'Tanda tangan berhasil disimpan! Semua approval sudah lengkap (6/6). Tanda tangan otomatis ter-copy ke SEMUA code barang dalam component ini.';
                $message_type = 'success';
            } else {
                // Update status to partial
                $conn->query("UPDATE color_approvals SET status_approval = 'partial' WHERE id = $color_approval_id");
                
                $message = 'Tanda tangan berhasil disimpan!';
                $message_type = 'success';
            }
            
            // Log activity
            create_audit_log($conn, 'Signature Created', $approval_id, 'approval', "Signed color ID: $color_id, Component ID: $component_id by " . $jabatan);
        } else {
            $message = 'Gagal menyimpan tanda tangan. Silakan coba lagi.';
            $message_type = 'error';
        }
        
        $update_stmt->close();
    }
}

skip_save:

// Get filter parameters
$filter_buyer = isset($_GET['buyer']) ? intval($_GET['buyer']) : 0;
$filter_component = isset($_GET['component']) ? intval($_GET['component']) : 0;

// Get all buyers for filter
$buyers_query = "SELECT DISTINCT b.id, b.nama_buyer FROM buyers b 
                 INNER JOIN master_color_panel mcp ON b.id = mcp.buyer_id 
                 ORDER BY b.nama_buyer ASC";
$buyers_result = $conn->query($buyers_query);

// Get all components for filter
$components_query = "SELECT DISTINCT cc.id, cc.component_name FROM color_components cc
                     INNER JOIN color_panel_components cpc ON cc.id = cpc.component_id
                     ORDER BY cc.component_name ASC";
$components_result = $conn->query($components_query);

// Build WHERE clause for filters
$where_conditions = ["1=1"];
$where_params = [];
$where_types = "";

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

if ($filter_component > 0) {
    $where_conditions[] = "cpc.component_id = ?";
    $where_params[] = $filter_component;
    $where_types .= "i";
}

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

// Get all color codes with their components
$all_colors_sql = "
    SELECT DISTINCT
        mcp.id as color_id,
        mcp.code_color,
        mcp.deskripsi,
        mcp.lemari,
        b.id as buyer_id,
        b.nama_buyer,
        c.nama_collection
    FROM master_color_panel mcp
    INNER JOIN buyers b ON mcp.buyer_id = b.id
    INNER JOIN collections c ON mcp.collection_id = c.id
    INNER JOIN color_panel_components cpc ON mcp.id = cpc.color_id
    WHERE $where_clause
    ORDER BY mcp.code_color ASC
";

if (!empty($where_types)) {
    $all_stmt = $conn->prepare($all_colors_sql);
    $all_stmt->bind_param($where_types, ...$where_params);
    $all_stmt->execute();
    $all_colors = $all_stmt->get_result();
} else {
    $all_colors = $conn->query($all_colors_sql);
}

// Process color codes with components
$grouped_colors = [];
if ($all_colors && $all_colors->num_rows > 0) {
    while ($color_row = $all_colors->fetch_assoc()) {
        $color_id = $color_row['color_id'];
        
        if (!isset($grouped_colors[$color_id])) {
            $grouped_colors[$color_id] = $color_row;
            $grouped_colors[$color_id]['components'] = [];
        }
        
        // Get all components for this color with their stock items count
        $components_query = "
            SELECT 
                cc.id as component_id,
                cc.component_name,
                COUNT(DISTINCT csi.id) as stock_count,
                MIN(csi.id) as first_stock_id,
                MIN(csi.kode_barang) as first_kode_barang
            FROM color_panel_components cpc
            INNER JOIN color_components cc ON cpc.component_id = cc.id
            LEFT JOIN color_stock_items csi ON cpc.color_id = csi.color_id AND cpc.component_id = csi.component_id
            LEFT JOIN color_approvals ca ON cpc.color_id = ca.color_id AND cpc.component_id = ca.component_id
            WHERE cpc.color_id = $color_id
            " . ($filter_component > 0 ? "AND cpc.component_id = $filter_component" : "") . "
            GROUP BY cc.id, cc.component_name
            ORDER BY cc.component_name ASC
        ";
        
        $components_result = $conn->query($components_query);
        
        while ($comp_row = $components_result->fetch_assoc()) {
            // Get approval status for this component
            $approval_query = "
                SELECT 
                    ca.id as approval_id,
                    ca.ka_unit_approved_by,
                    ca.color_room_approved_by,
                    ca.akzonobel_approved_by,
                    ca.approved_by_approved_by,
                    ca.qc_approved_by,
                    ca.qc_buyer_approved_by,
                    ca.status_approval
                FROM color_approvals ca
                WHERE ca.color_id = $color_id 
                AND ca.component_id = {$comp_row['component_id']}
            ";
            
            $approval_result = $conn->query($approval_query);
            $approval_data = $approval_result->fetch_assoc();
            
            $comp_row['approval_data'] = $approval_data;
            
            $grouped_colors[$color_id]['components'][] = $comp_row;
        }
    }
}

// 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-signature text-purple-600 mr-2"></i>
                    Tanda Tangan Color Code
                </h2>
                <p class="text-gray-600 mt-1">Pilih component untuk tanda tangan</p>
            </div>
            <div class="text-right">
                <p class="text-sm text-gray-500">Jabatan</p>
                <p class="text-lg font-semibold text-purple-600"><?php echo htmlspecialchars($jabatan); ?></p>
            </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; ?>

    <!-- Filter Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-filter text-purple-600 mr-2"></i>
            Filter Color Code
        </h3>
        <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Buyer</label>
                <select name="buyer" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                    <option value="0">Semua Buyer</option>
                    <?php 
                    if ($buyers_result && $buyers_result->num_rows > 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;
                    endif;
                    ?>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Component</label>
                <select name="component" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                    <option value="0">Semua Component</option>
                    <?php 
                    if ($components_result && $components_result->num_rows > 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;
                    endif;
                    ?>
                </select>
            </div>
            
            <div class="flex items-end gap-2">
                <button type="submit" class="flex-1 px-6 py-2 bg-gradient-to-r from-purple-500 to-purple-600 text-white rounded-lg hover:from-purple-600 hover:to-purple-700 transition-all duration-200">
                    <i class="fas fa-search mr-2"></i>
                    Filter
                </button>
                <a href="tanda_tangan.php" class="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">
                    <i class="fas fa-redo mr-2"></i>
                    Reset
                </a>
            </div>
        </form>
    </div>

    <!-- Info Box -->
    <div class="mb-6 bg-blue-50 border-l-4 border-blue-500 p-4 rounded">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-info-circle text-blue-500 text-xl"></i>
            </div>
            <div class="ml-3">
                <h3 class="text-sm font-semibold text-blue-800">Cara Kerja Sistem Approval</h3>
                <div class="mt-2 text-sm text-blue-700">
                    <ul class="list-disc list-inside space-y-1">
                        <li><strong>Klik Component:</strong> Pilih component yang ingin ditandatangani</li>
                        <li><strong>1 Perwakilan Code Barang:</strong> 1 code barang mewakili semua code barang dalam component tersebut</li>
                        <li><strong>Otomatis Copy:</strong> Saat 6/6 approval lengkap, tanda tangan otomatis ter-copy ke SEMUA code barang dalam component</li>
                        <li><strong>Status:</strong> Hijau = Sudah TTD | Orange = Belum TTD | Kuning = Partial (1-5 TTD)</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- All Colors List -->
    <div class="space-y-6">
        <?php if (count($grouped_colors) > 0): ?>
            <?php 
            $no = 1;
            foreach ($grouped_colors as $color_id => $color): 
            ?>
            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                <!-- Color Header -->
                <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-4">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-4">
                            <span class="text-white font-bold text-lg">#<?php echo $no++; ?></span>
                            <div>
                                <h3 class="text-xl font-bold text-white"><?php echo htmlspecialchars($color['code_color']); ?></h3>
                                <p class="text-purple-100 text-sm"><?php echo htmlspecialchars($color['deskripsi']); ?> | Lemari: <?php echo htmlspecialchars($color['lemari']); ?></p>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-purple-100 text-sm"><?php echo htmlspecialchars($color['nama_buyer']); ?></p>
                            <p class="text-purple-200 text-xs"><?php echo htmlspecialchars($color['nama_collection']); ?></p>
                        </div>
                    </div>
                </div>

                <!-- Components Grid -->
                <div class="p-6">
                    <h4 class="text-sm font-semibold text-gray-700 mb-3">
                        <i class="fas fa-cubes mr-2"></i>
                        Pilih Component untuk Tanda Tangan:
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <?php foreach ($color['components'] as $component): 
                            $approval = $component['approval_data'];
                            
                            // Count signatures
                            $signatures_done = 0;
                            if ($approval) {
                                if ($approval['ka_unit_approved_by']) $signatures_done++;
                                if ($approval['color_room_approved_by']) $signatures_done++;
                                if ($approval['akzonobel_approved_by']) $signatures_done++;
                                if ($approval['approved_by_approved_by']) $signatures_done++;
                                if ($approval['qc_approved_by']) $signatures_done++;
                                if ($approval['qc_buyer_approved_by']) $signatures_done++;
                            }
                            
                            // Check if current user signed
                            $current_user_signed = ($approval && $approval[$approval_mapping['column']] != null);
                            
                            // Determine status color
                            if ($signatures_done == 6) {
                                $status_class = 'border-green-500 bg-green-50';
                                $badge_class = 'bg-green-100 text-green-800';
                                $icon_class = 'text-green-500';
                            } elseif ($current_user_signed) {
                                $status_class = 'border-blue-500 bg-blue-50';
                                $badge_class = 'bg-blue-100 text-blue-800';
                                $icon_class = 'text-blue-500';
                            } elseif ($signatures_done > 0) {
                                $status_class = 'border-yellow-500 bg-yellow-50';
                                $badge_class = 'bg-yellow-100 text-yellow-800';
                                $icon_class = 'text-yellow-500';
                            } else {
                                $status_class = 'border-gray-300 bg-white hover:border-purple-500 hover:bg-purple-50 cursor-pointer';
                                $badge_class = 'bg-gray-100 text-gray-800';
                                $icon_class = 'text-gray-400';
                            }
                        ?>
                        <div class="component-card border-2 <?php echo $status_class; ?> rounded-lg p-4 transition-all duration-200"
                             data-color-id="<?php echo $color_id; ?>"
                             data-component-id="<?php echo $component['component_id']; ?>"
                             data-component-name="<?php echo htmlspecialchars($component['component_name']); ?>"
                             data-stock-id="<?php echo $component['first_stock_id']; ?>"
                             data-kode-barang="<?php echo htmlspecialchars($component['first_kode_barang']); ?>"
                             data-signed="<?php echo $current_user_signed ? '1' : '0'; ?>"
                             data-completed="<?php echo ($signatures_done == 6) ? '1' : '0'; ?>"
                             <?php if (!$current_user_signed && $signatures_done < 6): ?>
                             onclick="selectComponent(this, '<?php echo htmlspecialchars($color['code_color']); ?>')"
                             <?php endif; ?>>
                            
                            <div class="flex items-start justify-between mb-3">
                                <div class="flex-1">
                                    <h5 class="font-semibold text-gray-900 mb-1"><?php echo htmlspecialchars($component['component_name']); ?></h5>
                                    <p class="text-xs text-gray-600">
                                        <i class="fas fa-box mr-1"></i>
                                        <?php echo $component['stock_count']; ?> code barang
                                    </p>
                                </div>
                                <i class="fas fa-check-circle <?php echo $icon_class; ?> text-2xl"></i>
                            </div>
                            
                            <!-- Status Badge -->
                            <div class="flex items-center justify-between">
                                <span class="px-2 py-1 <?php echo $badge_class; ?> text-xs rounded-full font-semibold">
                                    <?php echo $signatures_done; ?>/6 TTD
                                </span>
                                
                                <?php if ($current_user_signed): ?>
                                    <span class="text-xs text-blue-600 font-semibold">
                                        <i class="fas fa-user-check mr-1"></i>Anda Sudah TTD
                                    </span>
                                <?php elseif ($signatures_done == 6): ?>
                                    <span class="text-xs text-green-600 font-semibold">
                                        <i class="fas fa-lock mr-1"></i>Lengkap
                                    </span>
                                <?php else: ?>
                                    <span class="text-xs text-purple-600 font-semibold">
                                        <i class="fas fa-hand-pointer mr-1"></i>Klik untuk TTD
                                    </span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Perwakilan Code -->
                            <div class="mt-2 pt-2 border-t border-gray-200">
                                <p class="text-xs text-gray-500">
                                    <i class="fas fa-barcode mr-1"></i>
                                    Perwakilan: <span class="font-mono"><?php echo htmlspecialchars($component['first_kode_barang']); ?></span>
                                </p>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
        <div class="bg-white rounded-lg shadow-md 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">Tidak Ada Color Code</h3>
            <p class="text-gray-500">Tidak ada color code yang sesuai dengan filter.</p>
            <a href="dashboard_approval.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-home mr-2"></i>
                Kembali ke Dashboard
            </a>
        </div>
        <?php endif; ?>
    </div>

    <!-- Floating Action Button -->
    <div id="floatingButton" class="hidden fixed bottom-8 right-8 z-30">
        <button id="signButton" 
                disabled
                class="px-6 py-4 bg-gradient-to-r from-purple-500 to-purple-600 text-white rounded-full shadow-2xl hover:from-purple-600 hover:to-purple-700 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-3">
            <i class="fas fa-signature text-2xl"></i>
            <div class="text-left">
                <div class="font-bold">Tanda Tangan</div>
                <div class="text-xs opacity-90" id="selectedComponentName">Pilih component dulu</div>
            </div>
        </button>
    </div>

</main>

<!-- Signature Modal -->
<div id="signatureModal" 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-purple-500 to-purple-600 px-6 py-4 flex justify-between items-center">
            <h3 class="text-xl font-bold text-white">
                <i class="fas fa-signature mr-2"></i>
                Buat Tanda Tangan
            </h3>
            <button onclick="closeSignatureModal()" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        
        <form method="POST" id="signatureForm">
            <div class="p-6">
                <!-- Color & Component Info -->
                <div class="mb-4 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="modalColorCode">-</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Component:</p>
                            <p class="font-semibold text-gray-900" id="modalComponentName">-</p>
                        </div>
                    </div>
                    <div class="mt-2">
                        <p class="text-sm text-gray-600">Kode Barang (Perwakilan):</p>
                        <p class="font-mono text-sm font-semibold text-gray-900" id="modalKodeBarang">-</p>
                    </div>
                    <div class="mt-3 p-3 bg-blue-50 rounded border border-blue-200">
                        <p class="text-xs text-blue-800">
                            <i class="fas fa-info-circle mr-1"></i>
                            <strong>Info:</strong> Tanda tangan ini mewakili 1 Component. Saat 6/6 approval lengkap, otomatis ter-copy ke SEMUA code barang dalam component ini.
                        </p>
                    </div>
                </div>

                <!-- Signature Canvas -->
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Tanda Tangan
                        Anda
                    </label>
                    <div class="border-2 border-gray-300 rounded-lg overflow-hidden bg-white">
                        <canvas id="signatureCanvas" 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> 
                        Gunakan mouse atau touchscreen untuk membuat tanda tangan
                    </p>
                </div>

                <!-- Buttons -->
                <div class="flex space-x-3">
                    <button type="button" onclick="clearSignature()" 
                            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="saveSignature()" 
                            class="flex-1 px-4 py-2 bg-gradient-to-r from-purple-500 to-purple-600 text-white rounded-lg hover:from-purple-600 hover:to-purple-700 transition-all duration-200">
                        <i class="fas fa-save mr-2"></i>
                        Simpan Tanda Tangan
                    </button>
                </div>

                <!-- Warning -->
                <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <p class="text-sm text-yellow-800">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        <strong>Perhatian:</strong> Anda hanya memiliki 1 kesempatan untuk mengedit tanda tangan. Pastikan tanda tangan sudah benar sebelum menyimpan.
                    </p>
                </div>
            </div>

            <input type="hidden" name="color_id" id="colorId">
            <input type="hidden" name="component_id" id="componentId">
            <input type="hidden" name="stock_item_id" id="stockItemId">
            <input type="hidden" name="signature_data" id="signatureData">
            <input type="hidden" name="save_signature" value="1">
        </form>
    </div>
</div>

<style>
.component-card.selected {
    border-color: #7c3aed !important;
    background-color: #f3e8ff !important;
    transform: scale(1.02);
    box-shadow: 0 10px 25px -5px rgba(124, 58, 237, 0.3);
}

.component-card:not([data-signed="1"]):not([data-completed="1"]):hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>

<script>
// Signature canvas setup
let canvas, ctx;
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let selectedComponent = null;

document.addEventListener('DOMContentLoaded', function() {
    canvas = document.getElementById('signatureCanvas');
    ctx = canvas.getContext('2d');
    
    // Set canvas background to white
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Set drawing styles
    ctx.strokeStyle = '#000000';
    ctx.lineWidth = 2;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    
    // Mouse events
    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mouseup', stopDrawing);
    canvas.addEventListener('mouseout', stopDrawing);
    
    // Touch events for mobile
    canvas.addEventListener('touchstart', handleTouchStart);
    canvas.addEventListener('touchmove', handleTouchMove);
    canvas.addEventListener('touchend', stopDrawing);
    
    // Setup sign button
    document.getElementById('signButton').addEventListener('click', function() {
        if (selectedComponent) {
            openSignatureModal();
        }
    });
});

function startDrawing(e) {
    isDrawing = true;
    const rect = canvas.getBoundingClientRect();
    lastX = e.clientX - rect.left;
    lastY = e.clientY - rect.top;
}

function draw(e) {
    if (!isDrawing) return;
    
    const rect = canvas.getBoundingClientRect();
    const currentX = e.clientX - rect.left;
    const currentY = e.clientY - rect.top;
    
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(currentX, currentY);
    ctx.stroke();
    
    lastX = currentX;
    lastY = currentY;
}

function stopDrawing() {
    isDrawing = false;
}

function handleTouchStart(e) {
    e.preventDefault();
    const touch = e.touches[0];
    const rect = canvas.getBoundingClientRect();
    isDrawing = true;
    lastX = touch.clientX - rect.left;
    lastY = touch.clientY - rect.top;
}

function handleTouchMove(e) {
    if (!isDrawing) return;
    e.preventDefault();
    
    const touch = e.touches[0];
    const rect = canvas.getBoundingClientRect();
    const currentX = touch.clientX - rect.left;
    const currentY = touch.clientY - rect.top;
    
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(currentX, currentY);
    ctx.stroke();
    
    lastX = currentX;
    lastY = currentY;
}

function clearSignature() {
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function selectComponent(element, colorCode) {
    // Check if already signed or completed
    const isSigned = element.getAttribute('data-signed') === '1';
    const isCompleted = element.getAttribute('data-completed') === '1';
    
    if (isSigned || isCompleted) {
        return; // Cannot select
    }
    
    // Remove previous selection
    const allCards = document.querySelectorAll('.component-card');
    allCards.forEach(card => card.classList.remove('selected'));
    
    // Add selection to current card
    element.classList.add('selected');
    
    // Store selected component data
    selectedComponent = {
        colorId: element.getAttribute('data-color-id'),
        colorCode: colorCode,
        componentId: element.getAttribute('data-component-id'),
        componentName: element.getAttribute('data-component-name'),
        stockId: element.getAttribute('data-stock-id'),
        kodeBarang: element.getAttribute('data-kode-barang')
    };
    
    // Enable sign button and show it
    const signButton = document.getElementById('signButton');
    const floatingButton = document.getElementById('floatingButton');
    const selectedComponentName = document.getElementById('selectedComponentName');
    
    signButton.disabled = false;
    floatingButton.classList.remove('hidden');
    selectedComponentName.textContent = selectedComponent.componentName;
    
    // Scroll to show the button
    floatingButton.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

function openSignatureModal() {
    if (!selectedComponent) return;
    
    document.getElementById('colorId').value = selectedComponent.colorId;
    document.getElementById('componentId').value = selectedComponent.componentId;
    document.getElementById('stockItemId').value = selectedComponent.stockId;
    document.getElementById('modalColorCode').textContent = selectedComponent.colorCode;
    document.getElementById('modalComponentName').textContent = selectedComponent.componentName;
    document.getElementById('modalKodeBarang').textContent = selectedComponent.kodeBarang;
    document.getElementById('signatureModal').classList.remove('hidden');
    clearSignature();
}

function closeSignatureModal() {
    document.getElementById('signatureModal').classList.add('hidden');
    clearSignature();
}

function saveSignature() {
    // Check if canvas is empty
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const pixels = imageData.data;
    let isEmpty = true;
    
    for (let i = 0; i < pixels.length; i += 4) {
        // Check if any pixel is not white
        if (pixels[i] !== 255 || pixels[i + 1] !== 255 || pixels[i + 2] !== 255) {
            isEmpty = false;
            break;
        }
    }
    
    if (isEmpty) {
        alert('Tanda tangan tidak boleh kosong!');
        return;
    }
    
    // Convert canvas to base64
    const signatureData = canvas.toDataURL('image/png');
    document.getElementById('signatureData').value = signatureData;
    
    // Submit form
    if (confirm('Apakah Anda yakin ingin menyimpan tanda tangan ini untuk component "' + selectedComponent.componentName + '"?\n\nAnda hanya memiliki 1 kesempatan untuk mengedit tanda tangan.')) {
        document.getElementById('signatureForm').submit();
    }
}

// Close modal when clicking outside
document.getElementById('signatureModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeSignatureModal();
    }
});
</script>

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