<?php
session_start();
require_once 'includes/auth_helpers.php';
require_once 'db/config.php';

// Protect route: check if user is logged in and has permission
redirect_if_not_authenticated();
redirect_if_no_permission('manage_users');

$user = $_SESSION['user'];

// Dynamic project data from environment
$projectName = $_SERVER['PROJECT_NAME'] ?? 'Customer Master';
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? 'Customer Master Registration & Maintenance';
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? '';

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['userCsv'])) {
    $file = $_FILES['userCsv'];

    if ($file['error'] === UPLOAD_ERR_OK) {
        $csvData = array_map('str_getcsv', file($file['tmp_name']));
        $header = array_shift($csvData);
        $expectedHeader = ['username', 'password', 'role'];

        if ($header === $expectedHeader) {
            $pdo = db();
            $pdo->beginTransaction();
            $createdCount = 0;
            $errorCount = 0;
            $errors = [];

            // Get all roles from the database
            $stmt = $pdo->query("SELECT id, name FROM roles");
            $roles = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
            
            foreach ($csvData as $rowIndex => $row) {
                $username = $row[0] ?? null;
                $password = $row[1] ?? null;
                $roleName = $row[2] ?? null;

                if (empty($username) || empty($password) || empty($roleName)) {
                    $errorCount++;
                    $errors[] = "Row " . ($rowIndex + 2) . ": Invalid data.";
                    continue;
                }
                
                if (!in_array($roleName, $roles)) {
                    $errorCount++;
                    $errors[] = "Row " . ($rowIndex + 2) . ": Role '".htmlspecialchars($roleName)."' does not exist.";
                    continue;
                }

                $roleId = array_search($roleName, $roles);

                try {
                    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
                    $stmt->execute([$username]);
                    if ($stmt->fetch()) {
                        $errorCount++;
                        $errors[] = "Row " . ($rowIndex + 2) . ": User '".htmlspecialchars($username)."' already exists.";
                        continue;
                    }

                    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("INSERT INTO users (username, password, role_id) VALUES (?, ?, ?)");
                    $stmt->execute([$username, $hashedPassword, $roleId]);
                    $createdCount++;
                } catch (PDOException $e) {
                    $errorCount++;
                    $errors[] = "Row " . ($rowIndex + 2) . ": Database error.";
                }
            }

            if ($errorCount > 0) {
                $pdo->rollBack();
                $_SESSION['flash_message'] = [
                    'type' => 'danger',
                    'message' => "User import failed with {$errorCount} errors.",
                    'errors' => $errors
                ];
            } else {
                $pdo->commit();
                $_SESSION['flash_message'] = [
                    'type' => 'success',
                    'message' => "Successfully created {$createdCount} users."
                ];
            }
        } else {
            $_SESSION['flash_message'] = [
                'type' => 'danger',
                'message' => 'Invalid CSV header. Expected: username,password,role'
            ];
        }
    } else {
        $_SESSION['flash_message'] = [
            'type' => 'danger',
            'message' => 'Error uploading file.'
        ];
    }
    header('Location: manage_users.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Users - <?php echo htmlspecialchars($projectName); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="index.php"><i class="bi bi-person-vcard"></i> <?php echo htmlspecialchars($projectName); ?></a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="mainNav">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Dashboard</a>
                    </li>
                    <?php if (hasPermission('manage_users')): ?>
                    <li class="nav-item">
                        <a class="nav-link active" href="manage_users.php">Manage Users</a>
                    </li>
                    <?php endif; ?>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle"></i> <?php echo htmlspecialchars($user['username']); ?>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="profile.php">Profile</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="bi bi-box-arrow-right"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            }
            </div>
        </div>
    </nav>

    <main class="container mt-4">
        <?php if (isset($_SESSION['flash_message'])): ?>
            <div class="alert alert-<?php echo $_SESSION['flash_message']['type']; ?> alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['flash_message']['message']; ?>
                <?php if (!empty($_SESSION['flash_message']['errors'])): ?>
                    <ul>
                        <?php foreach ($_SESSION['flash_message']['errors'] as $error): ?>
                            <li><?php echo $error; ?></li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['flash_message']); ?>
        <?php endif; ?>

        <h1 class="h3 mb-4">Manage Users</h1>
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Import Users from CSV</h5>
            </div>
            <div class="card-body">
                <p>Upload a CSV file with the following columns: <strong>username</strong>, <strong>password</strong>, <strong>role</strong>.</p>
                <form action="manage_users.php" method="post" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="userCsv" class="form-label">CSV File</label>
                        <input class="form-control" type="file" id="userCsv" name="userCsv" accept=".csv" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Import Users</button>
                </form>
            </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
