<?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'];
$stmt = $conn->prepare("SELECT * FROM approval_users WHERE id = ?");
$stmt->bind_param("i", $approval_id);
$stmt->execute();
$approval_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Set page title
$page_title = "Dashboard Approval";

// Log activity
create_audit_log($conn, 'Dashboard Access', $approval_id, 'approval', 'Approval user accessed dashboard');

// Get user's jabatan for determining which column to check
$jabatan = $_SESSION['jabatan'];
$column_mapping = [
    'K A Unit' => 'ka_unit_approved_by',
    'Color Room' => 'color_room_approved_by',
    'Akzonobel' => 'akzonobel_approved_by',
    'Approved by' => 'approved_by_approved_by',
    'Approved by QC' => 'qc_approved_by',
    'Approved by QC Buyer' => 'qc_buyer_approved_by'
];

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

// Get statistics for dashboard

// 1. Total Color Codes in System
$total_colors_stmt = $conn->prepare("SELECT COUNT(*) as total FROM master_color_panel");
$total_colors_stmt->execute();
$total_colors = $total_colors_stmt->get_result()->fetch_assoc()['total'];
$total_colors_stmt->close();

// 2. Total Components in System
$total_components_stmt = $conn->prepare("
    SELECT COUNT(DISTINCT cpc.component_id) as total 
    FROM color_panel_components cpc
");
$total_components_stmt->execute();
$total_components = $total_components_stmt->get_result()->fetch_assoc()['total'];
$total_components_stmt->close();

// 3. Total Pending Component Approvals (components that need this user's signature)
$pending_approvals = 0;
if ($approval_column) {
    // Count components (per color+component) that need this user's signature
    $pending_stmt = $conn->prepare("
        SELECT COUNT(*) as total 
        FROM (
            SELECT DISTINCT cpc.color_id, cpc.component_id
            FROM color_panel_components cpc
            LEFT JOIN color_approvals ca ON cpc.color_id = ca.color_id AND cpc.component_id = ca.component_id
            WHERE ca.id IS NULL OR ca.$approval_column IS NULL
        ) as pending_count
    ");
    $pending_stmt->execute();
    $pending_approvals = $pending_stmt->get_result()->fetch_assoc()['total'];
    $pending_stmt->close();
}

// 4. Total Signed by Me (components already signed by this user)
$signed_by_me = 0;
if ($approval_column) {
    $signed_stmt = $conn->prepare("
        SELECT COUNT(*) as total 
        FROM color_approvals 
        WHERE $approval_column = ?
    ");
    $signed_stmt->bind_param("i", $approval_id);
    $signed_stmt->execute();
    $signed_by_me = $signed_stmt->get_result()->fetch_assoc()['total'];
    $signed_stmt->close();
}

// 5. Total Completed Approvals (all 6 signatures done for components)
$completed_stmt = $conn->prepare("
    SELECT COUNT(*) as total 
    FROM color_approvals 
    WHERE status_approval = 'completed'
");
$completed_stmt->execute();
$completed_approvals = $completed_stmt->get_result()->fetch_assoc()['total'];
$completed_stmt->close();

// 6. Total Partial Approvals (some signatures done, not all for components)
$partial_stmt = $conn->prepare("
    SELECT COUNT(*) as total 
    FROM color_approvals 
    WHERE status_approval = 'partial'
");
$partial_stmt->execute();
$partial_approvals = $partial_stmt->get_result()->fetch_assoc()['total'];
$partial_stmt->close();

// 7. Check if user has edit signature remaining
$can_edit_signature = true;
$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) {
    $can_edit_signature = false;
}

// 8. Get recent activities (last 5 approvals by this user)
$recent_activities = [];
if ($approval_column) {
    $activities_stmt = $conn->prepare("
        SELECT 
            ca.id as approval_id,
            mcp.code_color,
            mcp.id as color_id,
            cc.component_name,
            cc.id as component_id,
            ca.status_approval,
            ah.approved_at
        FROM approval_history ah
        INNER JOIN color_approvals ca ON ah.color_approval_id = ca.id
        INNER JOIN master_color_panel mcp ON ca.color_id = mcp.id
        INNER JOIN color_components cc ON ca.component_id = cc.id
        WHERE ah.approved_by = ?
        ORDER BY ah.approved_at DESC
        LIMIT 5
    ");
    $activities_stmt->bind_param("i", $approval_id);
    $activities_stmt->execute();
    $activities_result = $activities_stmt->get_result();
    
    while ($activity = $activities_result->fetch_assoc()) {
        $recent_activities[] = $activity;
    }
    $activities_stmt->close();
}

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

<style>
/* Activity Card Hover Effect */
.activity-card {
    transition: all 0.3s ease;
}

.activity-card:hover {
    transform: translateX(5px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    cursor: pointer;
}

.activity-card:active {
    transform: translateX(3px);
}

/* Tooltip style */
.activity-tooltip {
    position: relative;
}

.activity-tooltip::after {
    content: 'Klik untuk lihat detail di history';
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%) translateY(-8px);
    background-color: #1f2937;
    color: white;
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 12px;
    white-space: nowrap;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s ease;
    z-index: 10;
}

.activity-tooltip::before {
    content: '';
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%) translateY(-2px);
    border: 6px solid transparent;
    border-top-color: #1f2937;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s ease;
}

.activity-tooltip:hover::after,
.activity-tooltip:hover::before {
    opacity: 1;
}
</style>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-purple-100 via-pink-100 to-purple-200">
    <!-- Welcome Section -->
    <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">Dashboard Approval</h2>
                <p class="text-gray-600 mt-1">Selamat datang, <?php echo htmlspecialchars($approval_data['nama_lengkap']); ?>!</p>
                <p class="text-sm text-gray-500 mt-1">
                    <span class="font-semibold">NIK:</span> <?php echo htmlspecialchars($approval_data['nik']); ?> | 
                    <span class="font-semibold">Jabatan:</span> <?php echo htmlspecialchars($approval_data['jabatan']); ?>
                </p>
            </div>
            <div class="text-right">
                <p class="text-sm text-gray-500">Akses terakhir</p>
                <p class="text-lg font-medium text-gray-800"><?php echo date('d M Y, H:i'); ?></p>
                <?php if (!$can_edit_signature): ?>
                <div class="mt-2">
                    <span class="px-3 py-1 bg-red-100 text-red-700 text-xs rounded-full">
                        <i class="fas fa-exclamation-circle"></i> Edit Signature Terpakai
                    </span>
                </div>
                <?php else: ?>
                <div class="mt-2">
                    <span class="px-3 py-1 bg-green-100 text-green-700 text-xs rounded-full">
                        <i class="fas fa-check-circle"></i> Edit Signature Tersedia
                    </span>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Dashboard Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-6">
        <!-- Total Color Codes - Abu -->
        <div class="bg-gradient-to-br from-gray-500 to-gray-600 rounded-lg shadow-md p-6 text-white">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-white bg-opacity-20 mr-4">
                    <i class="fas fa-palette text-2xl text-white"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Total Color Codes</h3>
                    <p class="text-3xl font-bold text-white"><?php echo $total_colors; ?></p>
                    <p class="text-sm text-gray-200"><?php echo $total_components; ?> Total Components</p>
                </div>
            </div>
        </div>

        <!-- Pending Approvals - Kuning -->
        <div class="bg-gradient-to-br from-yellow-500 to-yellow-600 rounded-lg shadow-md p-6 text-white cursor-pointer hover:shadow-lg hover:from-yellow-600 hover:to-yellow-700 transition-all duration-200" 
             onclick="window.location.href='tanda_tangan.php'">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-white bg-opacity-20 mr-4">
                    <i class="fas fa-clock text-2xl text-white"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Menunggu TTD Saya</h3>
                    <p class="text-3xl font-bold text-white"><?php echo $pending_approvals; ?></p>
                    <p class="text-sm text-yellow-100">Components perlu TTD</p>
                </div>
            </div>
        </div>

        <!-- Signed by Me - Hijau -->
        <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-lg shadow-md p-6 text-white cursor-pointer hover:shadow-lg hover:from-green-600 hover:to-green-700 transition-all duration-200" 
             onclick="window.location.href='history_tanda_tangan.php'">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-white bg-opacity-20 mr-4">
                    <i class="fas fa-check-circle text-2xl text-white"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Sudah TTD Saya</h3>
                    <p class="text-3xl font-bold text-white"><?php echo $signed_by_me; ?></p>
                    <p class="text-sm text-green-100">Components sudah TTD</p>
                </div>
            </div>
        </div>

        <!-- Completed Approvals - Biru -->
        <div class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg shadow-md p-6 text-white">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-white bg-opacity-20 mr-4">
                    <i class="fas fa-clipboard-check text-2xl text-white"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Approval Selesai</h3>
                    <p class="text-3xl font-bold text-white"><?php echo $completed_approvals; ?></p>
                    <p class="text-sm text-blue-100">Components 6/6 TTD Lengkap</p>
                </div>
            </div>
        </div>

        <!-- Partial Approvals - Orange -->
        <div class="bg-gradient-to-br from-orange-500 to-orange-600 rounded-lg shadow-md p-6 text-white">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-white bg-opacity-20 mr-4">
                    <i class="fas fa-tasks text-2xl text-white"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Sedang Proses</h3>
                    <p class="text-3xl font-bold text-white"><?php echo $partial_approvals; ?></p>
                    <p class="text-sm text-orange-100">Components TTD Belum Lengkap</p>
                </div>
            </div>
        </div>

        <!-- Edit Signature Status - Purple -->
        <div class="bg-gradient-to-br from-purple-500 to-purple-600 rounded-lg shadow-md p-6 text-white">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-white bg-opacity-20 mr-4">
                    <i class="fas fa-edit text-2xl text-white"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Edit Signature</h3>
                    <p class="text-3xl font-bold text-white"><?php echo $can_edit_signature ? '1' : '0'; ?></p>
                    <p class="text-sm text-purple-100">
                        <?php echo $can_edit_signature ? 'Kesempatan Tersedia' : 'Sudah Terpakai'; ?>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">
            <i class="fas fa-bolt text-yellow-500 mr-2"></i>
            Quick Actions
        </h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <a href="tanda_tangan.php" class="flex items-center p-4 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 shadow-md">
                <i class="fas fa-signature text-2xl mr-3"></i>
                <div>
                    <p class="font-semibold">Tanda Tangan</p>
                    <p class="text-sm opacity-90">Approve components</p>
                </div>
            </a>
            
            <a href="history_tanda_tangan.php" class="flex items-center p-4 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 transition-all duration-200 shadow-md">
                <i class="fas fa-history text-2xl mr-3"></i>
                <div>
                    <p class="font-semibold">Lihat History</p>
                    <p class="text-sm opacity-90">Riwayat tanda tangan</p>
                </div>
            </a>
            
            <a href="profile_approval.php" class="flex items-center p-4 bg-gradient-to-r from-green-500 to-green-600 text-white rounded-lg hover:from-green-600 hover:to-green-700 transition-all duration-200 shadow-md">
                <i class="fas fa-user text-2xl mr-3"></i>
                <div>
                    <p class="font-semibold">Profile</p>
                    <p class="text-sm opacity-90">Lihat & edit profile</p>
                </div>
            </a>
        </div>
    </div>

    <!-- Recent Activity -->
    <?php if (count($recent_activities) > 0): ?>
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-xl font-bold text-gray-800">
                <i class="fas fa-clock text-blue-500 mr-2"></i>
                Aktivitas Terakhir
            </h3>
            <a href="history_tanda_tangan.php" class="text-sm text-purple-600 hover:text-purple-700 font-medium flex items-center gap-1">
                Lihat Semua
                <i class="fas fa-arrow-right"></i>
            </a>
        </div>
        <div class="space-y-3">
            <?php foreach ($recent_activities as $activity): ?>
            <div class="activity-card activity-tooltip flex items-center justify-between p-3 bg-gray-50 rounded-lg border-l-4 border-purple-500"
                 onclick="window.location.href='history_tanda_tangan.php?highlight=<?php echo $activity['approval_id']; ?>#approval-<?php echo $activity['approval_id']; ?>'">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-signature text-purple-600"></i>
                    </div>
                    <div>
                        <p class="font-semibold text-gray-900">
                            <?php echo htmlspecialchars($activity['code_color']); ?> - <?php echo htmlspecialchars($activity['component_name']); ?>
                        </p>
                        <p class="text-xs text-gray-500 flex items-center gap-2">
                            <i class="fas fa-calendar-alt"></i>
                            <?php echo date('d M Y, H:i', strtotime($activity['approved_at'])); ?>
                        </p>
                    </div>
                </div>
                <div class="flex items-center gap-2">
                    <span class="px-3 py-1 text-xs rounded-full font-medium <?php echo $activity['status_approval'] == 'completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'; ?>">
                        <?php echo $activity['status_approval'] == 'completed' ? '6/6 Lengkap' : 'Partial'; ?>
                    </span>
                    <i class="fas fa-chevron-right text-gray-400"></i>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Information Section -->
    <div class="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">Informasi Penting</h3>
                <div class="mt-2 text-sm text-blue-700">
                    <ul class="list-disc list-inside space-y-1">
                        <li><strong>Sistem Baru:</strong> Approval sekarang per component dalam color code</li>
                        <li>Setiap component memerlukan 6 tanda tangan untuk approved (6/6)</li>
                        <li>Anda hanya memiliki <strong>1 kesempatan</strong> untuk mengedit tanda tangan</li>
                        <li>Setelah 6/6 approval lengkap, tanda tangan otomatis ter-copy ke SEMUA code barang dalam component tersebut</li>
                        <li>Klik component yang ingin ditandatangani, lalu klik tombol "Tanda Tangan"</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

</main>

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