<?php
/**
 * Safe OBGYN Dummy Data Seeder
 * This script safely inserts dummy data, ignoring duplicates and invalid entries
 */

session_start();
require_once '../config/database.php';

// Simple admin check
if (!isset($_SESSION['user_id'])) {
    die('<h1>Access Denied</h1><p>Please <a href="../login.php">login</a> first.</p>');
}

try {
    $db = getDB();
    $stmt = $db->prepare("SELECT role_id FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();

    if (!$user || ($user['role_id'] != 1 && $user['role_id'] != 2)) {
        die('<h1>Access Denied</h1><p>Admin access required.</p>');
    }
} catch (Exception $e) {
    die('<h1>Database Error</h1><p>' . $e->getMessage() . '</p>');
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Safe OBGYN Dummy Data Seeder</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
<div class='container mt-5'>
    <h1>Safe OBGYN Dummy Data Seeder</h1>
    <p>This script will safely insert dummy data, skipping duplicates and invalid entries.</p>

    <?php
    try {
        $db = getDB();
        $db->beginTransaction();

        $successCount = 0;
        $skipCount = 0;
        $errorCount = 0;
        $errors = [];

        // Function to safely execute INSERT IGNORE
        function safeInsert($db, $table, $data, &$successCount, &$skipCount, &$errorCount, &$errors) {
            try {
                // Build INSERT IGNORE query
                $columns = array_keys($data);
                $placeholders = str_repeat('?,', count($columns) - 1) . '?';

                $sql = "INSERT IGNORE INTO $table (" . implode(',', $columns) . ") VALUES ($placeholders)";
                $stmt = $db->prepare($sql);
                $stmt->execute(array_values($data));

                if ($stmt->rowCount() > 0) {
                    $successCount++;
                } else {
                    $skipCount++;
                }
            } catch (Exception $e) {
                $errorCount++;
                $errors[] = "Error inserting into $table: " . $e->getMessage();
            }
        }

        echo "<div class='alert alert-info'>Starting data insertion...</div>";

        // Insert roles
        $roles = [
            ['name' => 'role_01', 'description' => 'Dummy role role_01'],
            ['name' => 'role_02', 'description' => 'Dummy role role_02'],
            ['name' => 'role_03', 'description' => 'Dummy role role_03'],
            ['name' => 'role_04', 'description' => 'Dummy role role_04'],
            ['name' => 'role_05', 'description' => 'Dummy role role_05'],
            ['name' => 'role_06', 'description' => 'Dummy role role_06'],
            ['name' => 'role_07', 'description' => 'Dummy role role_07'],
            ['name' => 'role_08', 'description' => 'Dummy role role_08'],
            ['name' => 'role_09', 'description' => 'Dummy role role_09'],
            ['name' => 'role_10', 'description' => 'Dummy role role_10'],
            ['name' => 'role_11', 'description' => 'Dummy role role_11'],
            ['name' => 'role_12', 'description' => 'Dummy role role_12'],
            ['name' => 'role_13', 'description' => 'Dummy role role_13'],
            ['name' => 'role_14', 'description' => 'Dummy role role_14'],
            ['name' => 'role_15', 'description' => 'Dummy role role_15'],
            ['name' => 'role_16', 'description' => 'Dummy role role_16'],
            ['name' => 'role_17', 'description' => 'Dummy role role_17'],
            ['name' => 'role_18', 'description' => 'Dummy role role_18'],
            ['name' => 'role_19', 'description' => 'Dummy role role_19'],
            ['name' => 'role_20', 'description' => 'Dummy role role_20'],
        ];

        foreach ($roles as $role) {
            safeInsert($db, 'roles', $role, $successCount, $skipCount, $errorCount, $errors);
        }

        // Insert permissions
        $permissions = [
            ['name' => 'studies.perm_01', 'description' => 'Dummy permission 1', 'module' => 'studies'],
            ['name' => 'users.perm_02', 'description' => 'Dummy permission 2', 'module' => 'users'],
            ['name' => 'chat.perm_03', 'description' => 'Dummy permission 3', 'module' => 'chat'],
            ['name' => 'cms.perm_04', 'description' => 'Dummy permission 4', 'module' => 'cms'],
            ['name' => 'cms.perm_05', 'description' => 'Dummy permission 5', 'module' => 'cms'],
            ['name' => 'publications.perm_06', 'description' => 'Dummy permission 6', 'module' => 'publications'],
            ['name' => 'studies.perm_07', 'description' => 'Dummy permission 7', 'module' => 'studies'],
            ['name' => 'notifications.perm_08', 'description' => 'Dummy permission 8', 'module' => 'notifications'],
            ['name' => 'studies.perm_09', 'description' => 'Dummy permission 9', 'module' => 'studies'],
            ['name' => 'institutions.perm_10', 'description' => 'Dummy permission 10', 'module' => 'institutions'],
            ['name' => 'settings.perm_11', 'description' => 'Dummy permission 11', 'module' => 'settings'],
            ['name' => 'users.perm_12', 'description' => 'Dummy permission 12', 'module' => 'users'],
            ['name' => 'users.perm_13', 'description' => 'Dummy permission 13', 'module' => 'users'],
            ['name' => 'studies.perm_14', 'description' => 'Dummy permission 14', 'module' => 'studies'],
            ['name' => 'cms.perm_15', 'description' => 'Dummy permission 15', 'module' => 'cms'],
            ['name' => 'cms.perm_16', 'description' => 'Dummy permission 16', 'module' => 'cms'],
            ['name' => 'notifications.perm_17', 'description' => 'Dummy permission 17', 'module' => 'notifications'],
            ['name' => 'institutions.perm_18', 'description' => 'Dummy permission 18', 'module' => 'institutions'],
        ];

        foreach ($permissions as $perm) {
            safeInsert($db, 'permissions', $perm, $successCount, $skipCount, $errorCount, $errors);
        }

        // Insert users with safe role lookup
        $users = [
            ['email' => 'ozgur.zaki.3@obgynresearch.com', 'password' => '$2y$12$pseimvihcwi64ciyhe7ur23gdppq0y9dom5igqpki7p5tb94874fr', 'first_name' => 'Ozgur', 'last_name' => 'Zaki', 'role_name' => 'role_07', 'status' => 'active', 'email_verified' => 0],
            ['email' => 'mahmoud.ali.4@obgynresearch.com', 'password' => '$2y$12$j2qp89uzfk8ut0cvs4f8cgvyie6ivwpvs7hzioykl1cq99chj755n', 'first_name' => 'Mahmoud', 'last_name' => 'Ali', 'role_name' => 'role_06', 'status' => 'suspended', 'email_verified' => 1],
            ['email' => 'ramy.zaki.5@medexample.org', 'password' => '$2y$12$a3kx7eedtjvzhwjr64dpja1wj0tpac56t4ufel6246hid25owf759', 'first_name' => 'Ramy', 'last_name' => 'Zaki', 'role_name' => 'role_06', 'status' => 'active', 'email_verified' => 0],
            ['email' => 'youssef2.hussein.6@obgynresearch.com', 'password' => '$2y$12$253j2d54i3qk2iagl58kxo9t7e8g8jdp0lvsnujza7tz0yncxll4z', 'first_name' => 'Youssef2', 'last_name' => 'Hussein', 'role_name' => 'guest', 'status' => 'suspended', 'email_verified' => 1],
            ['email' => 'sherif.younes.7@medexample.org', 'password' => '$2y$12$kep7y6wktakpuxqphr62gdswm31yihair4cowgzrixa11dpg8sbi4', 'first_name' => 'Sherif', 'last_name' => 'Younes', 'role_name' => 'institution_admin', 'status' => 'pending', 'email_verified' => 1],
            ['email' => 'lama.hamdy.8@medexample.org', 'password' => '$2y$12$36p6qf5q14j1ripzim6cfnfholqc3o18a5ur7ko64t026rjrny204', 'first_name' => 'Lama', 'last_name' => 'Hamdy', 'role_name' => 'researcher', 'status' => 'pending', 'email_verified' => 0],
            ['email' => 'nadia.zaki.9@obgynresearch.com', 'password' => '$2y$12$eqbnhl1n13jcat9mx2x18hafeyuhz1gv0e38daly8ozcywd14ve92', 'first_name' => 'Nadia', 'last_name' => 'Zaki', 'role_name' => 'role_12', 'status' => 'suspended', 'email_verified' => 1],
            ['email' => 'hassan.barakat.10@medexample.org', 'password' => '$2y$12$m43d8w3zp08j3trp0j43d5iqvnb4gh2m5zja8dzr1yxr2dhylurtp', 'first_name' => 'Hassan', 'last_name' => 'Barakat', 'role_name' => 'guest', 'status' => 'pending', 'email_verified' => 1],
            ['email' => 'lina.amin.11@obgynresearch.com', 'password' => '$2y$12$izl08yg0jv1v93kmkzebbk7w1dakrm8j5ecruyf38diuovw1n6kvp', 'first_name' => 'Lina', 'last_name' => 'Amin', 'role_name' => 'researcher', 'status' => 'suspended', 'email_verified' => 0],
            ['email' => 'lama.aziz.12@medexample.org', 'password' => '$2y$12$hxfgcaqvkizzqy72wx7ptx63cfl0ukeyz7srcbpljd84u89yjb1qx', 'first_name' => 'Lama', 'last_name' => 'Aziz', 'role_name' => 'institution_admin', 'status' => 'suspended', 'email_verified' => 1],
            ['email' => 'doaa.fathy.13@example.com', 'password' => '$2y$12$qoldforxo1bdje153a5qbswrpbjek5rbw2zlaoi4e8xf7kzorqqfg', 'first_name' => 'Doaa', 'last_name' => 'Fathy', 'role_name' => 'institution_admin', 'status' => 'active', 'email_verified' => 1],
            ['email' => 'jana.ashraf.14@obgynresearch.com', 'password' => '$2y$12$7s3kkv9rftmttqlgzui1b0z3nx39rbsv55psq0oxfq8myx444nlz1', 'first_name' => 'Jana', 'last_name' => 'Ashraf', 'role_name' => 'researcher', 'status' => 'suspended', 'email_verified' => 0],
            ['email' => 'dina.zaki.15@medexample.org', 'password' => '$2y$12$790pdw5py6b2knftu2gc5wi6fqjja26yfpmvxpj4hnriuu9k9xjuy', 'first_name' => 'Dina', 'last_name' => 'Zaki', 'role_name' => 'role_02', 'status' => 'pending', 'email_verified' => 0],
            ['email' => 'ghada.khalil.16@example.com', 'password' => '$2y$12$wwyzx4w6xlpu0dk0get8t63j3r30me8f840982n2atqyyv37dia5u', 'first_name' => 'Ghada', 'last_name' => 'Khalil', 'role_name' => 'institution_admin', 'status' => 'suspended', 'email_verified' => 0],
            ['email' => 'doaa.hamdy.17@medexample.org', 'password' => '$2y$12$kof8krd5eqy08p0fodro8bnp84dyt9moge4qxxva2ieuc1hh5lf6a', 'first_name' => 'Doaa', 'last_name' => 'Hamdy', 'role_name' => 'institution_admin', 'status' => 'suspended', 'email_verified' => 1],
            ['email' => 'mostafa.kamel.18@medexample.org', 'password' => '$2y$12$5em2vajepecqnvqhw06xkxb94pdzp6lfewvznvksp2ex5t5p5o3o0', 'first_name' => 'Mostafa', 'last_name' => 'Kamel', 'role_name' => 'role_11', 'status' => 'pending', 'email_verified' => 1],
            ['email' => 'yara.said.19@medexample.org', 'password' => '$2y$12$7c3dd03uvulemx15z8vmuhxid4n1u3493wxa73jgzlma5uofwb0hp', 'first_name' => 'Yara', 'last_name' => 'Said', 'role_name' => 'institution_admin', 'status' => 'pending', 'email_verified' => 1],
            ['email' => 'salim.hussein.20@medexample.org', 'password' => '$2y$12$v5f1bcppvohsmdyvslh9bh811kerpetiuymo0pqclpoxko8g8qynp', 'first_name' => 'Salim', 'last_name' => 'Hussein', 'role_name' => 'institution_admin', 'status' => 'pending', 'email_verified' => 1],
            ['email' => 'fady.mahmoud.21@obgynresearch.com', 'password' => '$2y$12$50h2cwtg1m8xfdjgf1c8wquuy5x9l8lpqw2vmcqbnkx9dvnu80b6u', 'first_name' => 'Fady', 'last_name' => 'Mahmoud', 'role_name' => 'guest', 'status' => 'suspended', 'email_verified' => 1],
            ['email' => 'ola.said.22@example.com', 'password' => '$2y$12$q349dxbz9svn7n1ybwmlunj48vfcx7lxxezduxlez896dysal8m1g', 'first_name' => 'Ola', 'last_name' => 'Said', 'role_name' => 'institution_admin', 'status' => 'active', 'email_verified' => 1],
            ['email' => 'karim.barakat.23@medexample.org', 'password' => '$2y$12$45bm1enf313fpoyipk0qtl3q4n89qkns832ejx5td44k1j6fp8hqm', 'first_name' => 'Karim', 'last_name' => 'Barakat', 'role_name' => 'role_01', 'status' => 'active', 'email_verified' => 1],
        ];

        foreach ($users as $userData) {
            // Get role_id safely
            $roleStmt = $db->prepare("SELECT id FROM roles WHERE name = ? LIMIT 1");
            $roleStmt->execute([$userData['role_name']]);
            $role = $roleStmt->fetch();

            if ($role) {
                $userInsert = [
                    'email' => $userData['email'],
                    'password' => $userData['password'],
                    'first_name' => $userData['first_name'],
                    'last_name' => $userData['last_name'],
                    'role_id' => $role['id'],
                    'status' => $userData['status'],
                    'email_verified' => $userData['email_verified'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                safeInsert($db, 'users', $userInsert, $successCount, $skipCount, $errorCount, $errors);
            } else {
                $skipCount++;
                $errors[] = "Role '{$userData['role_name']}' not found for user {$userData['email']}";
            }
        }

        $db->commit();

        echo "<div class='alert alert-success'>";
        echo "<h3>✓ Seeding Complete!</h3>";
        echo "<p><strong>Records inserted:</strong> $successCount</p>";
        echo "<p><strong>Records skipped (duplicates):</strong> $skipCount</p>";
        if ($errorCount > 0) {
            echo "<p><strong>Errors encountered:</strong> $errorCount</p>";
            echo "<details><summary>View Errors</summary><ul>";
            foreach ($errors as $error) {
                echo "<li>$error</li>";
            }
            echo "</ul></details>";
        }
        echo "</div>";

    } catch (Exception $e) {
        $db->rollBack();
        echo "<div class='alert alert-danger'>";
        echo "<h3>✗ Transaction Failed</h3>";
        echo "<p>" . $e->getMessage() . "</p>";
        echo "</div>";
    }
    ?>

    <a href="../admin/dashboard.php" class="btn btn-primary">Back to Dashboard</a>
</div>
</body>
</html>