<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();
$errors = [];
$success = false;
$user = null;

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id > 0) {
    $user = $db->get(
        "SELECT u.*, ur.role, ur.permissions
         FROM users u
         LEFT JOIN user_roles ur ON u.id = ur.user_id
         WHERE u.id = ?",
        [$id]
    );
    if (!$user) {
        $_SESSION['flash']['danger'] = 'User not found.';
        header('Location: users.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username    = trim($_POST['username'] ?? '');
    $email       = trim($_POST['email'] ?? '');
    $firstName   = trim($_POST['first_name'] ?? '');
    $lastName    = trim($_POST['last_name'] ?? '');
    $role        = trim($_POST['role'] ?? '');
    $region      = trim($_POST['region'] ?? 'usa');
    $status      = trim($_POST['status'] ?? 'pending');
    $password    = $_POST['password'] ?? '';

    if ($username === '') {
        $errors[] = 'Username is required.';
    }
    if ($email === '') {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email format.';
    }
    if ($firstName === '') {
        $errors[] = 'First name is required.';
    }
    if ($lastName === '') {
        $errors[] = 'Last name is required.';
    }
    if (!in_array($role, ['super_admin','admin','regional_admin','instructor','student'], true)) {
        $errors[] = 'Invalid role selected.';
    }
    if (!in_array($region, ['usa','europe','africa'], true)) {
        $errors[] = 'Invalid region selected.';
    }
    if (!in_array($status, ['active','inactive','suspended','pending'], true)) {
        $errors[] = 'Invalid status selected.';
    }

    // Check uniqueness
    $existing = $db->get("SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?", [$username, $email, $id]);
    if ($existing) {
        $errors[] = 'Username or email already exists.';
    }

    if (empty($errors)) {
        try {
            $userData = [
                'username' => $username,
                'email' => $email,
                'first_name' => $firstName,
                'last_name' => $lastName,
                'region' => $region,
                'status' => $status,
                'updated_at' => formatDate(),
            ];

            if ($password !== '') {
                $userData['password'] = hashPassword($password);
            }

            // Build permissions object from checkboxes (if any)
            $permArray = [];
            if (!empty($_POST['permissions']) && is_array($_POST['permissions'])) {
                foreach ($_POST['permissions'] as $p) {
                    $permArray[$p] = true;
                }
            }

            if ($id > 0) {
                $db->update('users', $userData, 'id = ?', [$id]);
                // Update role and permissions
                $db->update('user_roles', ['role' => $role, 'permissions' => !empty($permArray) ? json_encode($permArray) : null], 'user_id = ?', [$id]);
                $_SESSION['flash']['success'] = 'User updated successfully.';
            } else {
                $userData['created_at'] = formatDate();
                $userData['email_verified'] = 1;
                $userData['password'] = $password ? hashPassword($password) : hashPassword('Temp123!');
                $newId = $db->insert('users', $userData);
                // If no explicit per-user permissions were provided, fetch role defaults
                if (empty($permArray)) {
                    $roleRow = $db->get('SELECT permissions FROM roles WHERE role = ?', [$role]);
                    if ($roleRow && !empty($roleRow['permissions'])) {
                        $permArray = is_string($roleRow['permissions']) ? json_decode($roleRow['permissions'], true) : $roleRow['permissions'];
                    }
                }

                $db->insert('user_roles', ['user_id' => $newId, 'role' => $role, 'permissions' => !empty($permArray) ? json_encode($permArray) : null, 'assigned_at' => formatDate()]);
                $_SESSION['flash']['success'] = 'User created successfully.';
            }
            header('Location: users.php');
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (!$user && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $user = [
        'username' => '',
        'email' => '',
        'first_name' => '',
        'last_name' => '',
        'role' => 'student',
        'region' => 'usa',
        'status' => 'pending',
    ];
}

$pageTitle = $id > 0 ? 'Edit User' : 'Add User';
include __DIR__ . '/includes/header.php';
?>

<?php
// Prepare available permissions and assigned perms for the form
$availablePermissions = ['can_create_courses','can_create_assessments','can_view_reports','can_view_analytics','can_manage_users','manage_region','can_manage_roles','can_create_certificates'];
$assignedPerms = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['permissions']) && is_array($_POST['permissions'])) {
    $assignedPerms = $_POST['permissions'];
} elseif (!empty($user['permissions'])) {
    $decoded = is_string($user['permissions']) ? json_decode($user['permissions'], true) : $user['permissions'];
    if (is_array($decoded)) $assignedPerms = array_keys(array_filter($decoded));
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0"><?php echo htmlspecialchars($pageTitle); ?></h1>
    <p class="text-muted mb-0"><?php echo $id > 0 ? 'Update user details' : 'Create a new user account'; ?></p>
  </div>
  <div>
    <a href="users.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Users
    </a>
  </div>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
      <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
          <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
<?php endif; ?>

<div class="card">
  <div class="card-body">
    <form method="post" action="">
      <div class="row mb-3">
        <div class="col-md-6">
          <label for="username" class="form-label">Username</label>
          <input type="text" name="username" id="username" class="form-control" required value="<?php echo htmlspecialchars($_POST['username'] ?? ($user['username'] ?? '')); ?>">
        </div>
        <div class="col-md-6">
          <label for="email" class="form-label">Email</label>
          <input type="email" name="email" id="email" class="form-control" required value="<?php echo htmlspecialchars($_POST['email'] ?? ($user['email'] ?? '')); ?>">
        </div>
      </div>

      <div class="row mb-3">
        <div class="col-md-6">
          <label for="first_name" class="form-label">First Name</label>
          <input type="text" name="first_name" id="first_name" class="form-control" required value="<?php echo htmlspecialchars($_POST['first_name'] ?? ($user['first_name'] ?? '')); ?>">
        </div>
        <div class="col-md-6">
          <label for="last_name" class="form-label">Last Name</label>
          <input type="text" name="last_name" id="last_name" class="form-control" required value="<?php echo htmlspecialchars($_POST['last_name'] ?? ($user['last_name'] ?? '')); ?>">
        </div>
      </div>

      <div class="row mb-3">
        <div class="col-md-4">
          <label for="role" class="form-label">Role</label>
          <select name="role" id="role" class="form-select" required>
            <?php foreach (['super_admin','admin','regional_admin','instructor','student'] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php if( (($_POST['role'] ?? ($user['role'] ?? '')) === $opt) ) echo 'selected'; ?>><?php echo htmlspecialchars(ucwords(str_replace('_',' ',$opt))); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-8">
          <label class="form-label">Permissions (optional overrides)</label>
          <div class="d-flex flex-wrap gap-2">
            <?php foreach ($availablePermissions as $perm): ?>
              <div class="form-check">
                <input class="form-check-input" type="checkbox" name="permissions[]" value="<?php echo $perm; ?>" id="perm_<?php echo $perm; ?>" <?php if (in_array($perm, $assignedPerms)) echo 'checked'; ?>>
                <label class="form-check-label small" for="perm_<?php echo $perm; ?>"><?php echo $perm; ?></label>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
        <div class="col-md-4">
          <label for="region" class="form-label">Region</label>
          <select name="region" id="region" class="form-select" required>
            <?php foreach (['usa','europe','africa'] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php if( (($_POST['region'] ?? ($user['region'] ?? '')) === $opt) ) echo 'selected'; ?>><?php echo ucfirst($opt); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label for="status" class="form-label">Status</label>
          <select name="status" id="status" class="form-select" required>
            <?php foreach (['active','inactive','suspended','pending'] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php if( (($_POST['status'] ?? ($user['status'] ?? '')) === $opt) ) echo 'selected'; ?>><?php echo ucfirst($opt); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="row mb-3">
        <div class="col-md-6">
          <label for="password" class="form-label">Password <?php echo $id > 0 ? '(leave blank to keep current)' : ''; ?></label>
          <input type="password" name="password" id="password" class="form-control" <?php echo $id === 0 ? 'required' : ''; ?>>
        </div>
      </div>

      <div class="d-flex justify-content-end gap-2">
        <a href="users.php" class="btn btn-outline-secondary">Cancel</a>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-save me-2"></i><?php echo $id > 0 ? 'Update' : 'Create'; ?>
        </button>
      </div>
    </form>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
