<?php
require_once '../includes/auth.php';

if (!isAdmin()) {
    redirect('../login.php');
}


// Koneksi database manual
try {
    $host = 'localhost';
    $dbname = 'soca_osce';
    $username = 'root';
    $password = '';
    
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Koneksi database gagal: " . $e->getMessage());
}

// Cek apakah user adalah admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo "<h2>Akses Ditolak</h2>";
    echo "<p>Hanya admin yang bisa mengakses halaman ini.</p>";
    echo "<p>Role Anda: " . ($_SESSION['role'] ?? 'Tidak ada session') . "</p>";
    echo "<p><a href='../login.php'>Login sebagai Admin</a></p>";
    exit;
}

echo "<!DOCTYPE html>
<html>
<head>
    <title>Sync Data Penguji</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        table { border-collapse: collapse; margin: 20px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .match { background-color: #d4edda; }
        .mismatch { background-color: #f8d7da; }
        .btn { background-color: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 10px 0; }
        .debug { background: #f8f9fa; padding: 10px; margin: 10px 0; border-left: 4px solid #007bff; }
    </style>
</head>
<body>
    <h1>Sync Data Penguji</h1>";

// Debug info
echo "<div class='debug'>";
echo "<strong>Debug Info:</strong><br>";
echo "Session Role: " . ($_SESSION['role'] ?? 'null') . "<br>";
echo "Session User ID: " . ($_SESSION['user_id'] ?? 'null') . "<br>";
echo "Session Username: " . ($_SESSION['user_name'] ?? 'null') . "<br>";
echo "</div>";

try {
    // Ambil data penguji
    $penguji_list = $pdo->query("SELECT * FROM penguji ORDER BY id")->fetchAll();
    
    // Ambil data users penguji
    $users_list = $pdo->query("SELECT * FROM users WHERE role = 'penguji' ORDER BY id")->fetchAll();

    echo "<h3>Data Penguji (Tabel: penguji) - Total: " . count($penguji_list) . "</h3>";
    if (empty($penguji_list)) {
        echo "<p>Tidak ada data penguji</p>";
    } else {
        echo "<table>
        <tr><th>ID</th><th>Nama</th><th>NIP</th><th>Username yang Diharapkan</th></tr>";
        
        foreach ($penguji_list as $p) {
            $expected_username = $p['nip'] ?: strtolower(str_replace(' ', '', $p['nama']));
            echo "<tr>
            <td>{$p['id']}</td>
            <td>{$p['nama']}</td>
            <td>{$p['nip']}</td>
            <td>{$expected_username}</td>
            </tr>";
        }
        echo "</table>";
    }

    echo "<h3>Data Users Penguji (Tabel: users) - Total: " . count($users_list) . "</h3>";
    if (empty($users_list)) {
        echo "<p>Tidak ada data users dengan role penguji</p>";
    } else {
        echo "<table>
        <tr><th>ID</th><th>Username</th><th>Role</th><th>Status Match</th></tr>";
        
        foreach ($users_list as $u) {
            // Cari matching penguji
            $matched = false;
            $matched_name = '';
            $match_type = '';
            
            foreach ($penguji_list as $p) {
                $expected_username = $p['nip'] ?: strtolower(str_replace(' ', '', $p['nama']));
                if ($u['username'] == $expected_username) {
                    $matched = true;
                    $matched_name = $p['nama'];
                    $match_type = $p['nip'] ? 'by NIP' : 'by Name';
                    break;
                }
            }
            
            $status_class = $matched ? 'match' : 'mismatch';
            $status_text = $matched ? "Match: {$matched_name} ({$match_type})" : "TIDAK MATCH";
            
            echo "<tr class='{$status_class}'>
            <td>{$u['id']}</td>
            <td>{$u['username']}</td>
            <td>{$u['role']}</td>
            <td>{$status_text}</td>
            </tr>";
        }
        echo "</table>";
    }

    // Tampilkan mapping yang salah
    echo "<h3>Mapping yang Salah</h3>";
    $wrong_mappings = [];
    
    foreach ($users_list as $u) {
        $matched = false;
        foreach ($penguji_list as $p) {
            $expected_username = $p['nip'] ?: strtolower(str_replace(' ', '', $p['nama']));
            if ($u['username'] == $expected_username) {
                $matched = true;
                break;
            }
        }
        
        if (!$matched) {
            $wrong_mappings[] = $u;
        }
    }
    
    if (empty($wrong_mappings)) {
        echo "<p style='color: green;'>✓ Semua mapping sudah benar!</p>";
    } else {
        echo "<p style='color: red;'>✗ Ada " . count($wrong_mappings) . " mapping yang salah:</p>";
        echo "<ul>";
        foreach ($wrong_mappings as $wrong) {
            echo "<li>User '{$wrong['username']}' tidak match dengan penguji manapun</li>";
        }
        echo "</ul>";
    }

    // Fix data jika requested
    if (isset($_GET['fix'])) {
        echo "<h3>Memperbaiki Data...</h3>";
        $fixed_count = 0;
        $errors = [];
        
        foreach ($penguji_list as $penguji) {
            $expected_username = $penguji['nip'] ?: strtolower(str_replace(' ', '', $penguji['nama']));
            
            // Cek apakah user dengan username ini sudah ada
            $check = $pdo->prepare("SELECT id, username FROM users WHERE username = ?");
            $check->execute([$expected_username]);
            $existing_user = $check->fetch();
            
            if ($existing_user) {
                // Update role jika perlu
                if ($existing_user['role'] !== 'penguji') {
                    $update = $pdo->prepare("UPDATE users SET role = 'penguji' WHERE id = ?");
                    $update->execute([$existing_user['id']]);
                    echo "✓ Updated user {$existing_user['id']} ({$expected_username}) role to 'penguji'<br>";
                    $fixed_count++;
                } else {
                    echo "✓ User {$existing_user['id']} ({$expected_username}) sudah benar<br>";
                }
            } else {
                // Buat user baru
                $hashed_password = password_hash('password', PASSWORD_DEFAULT);
                $insert = $pdo->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, 'penguji')");
                $insert->execute([$expected_username, $hashed_password]);
                $new_user_id = $pdo->lastInsertId();
                echo "✓ Created new user: {$expected_username} (ID: {$new_user_id}) with password: 'password'<br>";
                $fixed_count++;
            }
        }
        
        echo "<br><strong style='color: green;'>Sync completed! {$fixed_count} data diperbaiki.</strong><br>";
        echo "<p><strong>Default password untuk semua penguji: 'password'</strong></p>";
        echo "<a href='sync_penguji.php' class='btn'>Lihat Data Lagi</a>";
    } else {
        if (!empty($wrong_mappings)) {
            echo "<br><a href='sync_penguji.php?fix=1' class='btn'>Fix/Sync Data Penguji</a>";
        }
    }

} catch (PDOException $e) {
    echo "<div style='color: red;'><strong>Error Database:</strong> " . $e->getMessage() . "</div>";
}

echo "<br><br>";
echo "<a href='penguji.php'>Kembali ke Kelola Penguji</a> | ";
echo "<a href='dashboard.php'>Kembali ke Dashboard</a>";

echo "</body></html>";
?>