76 lines
3.0 KiB
PHP
76 lines
3.0 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
require_once __DIR__ . "/../auth_helper.php";
|
|
require_login();
|
|
require_role(["Admin", "Adviser"]);
|
|
|
|
if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
|
$election_id = $_POST["election_id"] ?? "";
|
|
$student_id = $_POST["student_id"] ?? "";
|
|
$name = $_POST["name"] ?? "";
|
|
$email = $_POST["email"] ?? "";
|
|
$role = $_POST["role"] ?? "Officer";
|
|
$password = $_POST["password"] ?? "iloilohns";
|
|
|
|
if (!$election_id || !$student_id || !$name || !$email) {
|
|
die("Missing fields");
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
$pdo->beginTransaction();
|
|
|
|
// 1. Check if user already exists
|
|
$stmt = $pdo->prepare("SELECT id FROM users WHERE student_id = ? OR email = ?");
|
|
$stmt->execute([$student_id, $email]);
|
|
$existing = $stmt->fetch();
|
|
|
|
if ($existing) {
|
|
$user_id = $existing["id"];
|
|
// Update role if changed
|
|
$upd = $pdo->prepare("UPDATE users SET role = ? WHERE id = ?");
|
|
$upd->execute([$role, $user_id]);
|
|
} else {
|
|
// 1a. Create user in Supabase
|
|
$supabaseUser = SupabaseAuth::createUser($email, $password);
|
|
$supabase_uid = null;
|
|
if ($supabaseUser['error']) {
|
|
if (str_contains(strtolower($supabaseUser['error']), 'already registered')) {
|
|
$sbUser = SupabaseAuth::getUserByEmail($email);
|
|
$supabase_uid = $sbUser['id'] ?? null;
|
|
} else {
|
|
throw new Exception("Supabase Error: " . $supabaseUser['error']);
|
|
}
|
|
} else {
|
|
$supabase_uid = $supabaseUser['data']['id'] ?? null;
|
|
}
|
|
|
|
// Create new user locally
|
|
$user_id = uuid();
|
|
$stmt = $pdo->prepare("INSERT INTO users (id, supabase_uid, student_id, name, email, role) VALUES (?, ?, ?, ?, ?, ?)");
|
|
$stmt->execute([$user_id, $supabase_uid, $student_id, $name, $email, $role]);
|
|
}
|
|
|
|
// 2. Assign to election
|
|
$chk = $pdo->prepare("SELECT COUNT(*) FROM election_assignments WHERE election_id = ? AND user_id = ?");
|
|
$chk->execute([$election_id, $user_id]);
|
|
if ($chk->fetchColumn() == 0) {
|
|
$role_in_election = $role; // Admin, Adviser, or Officer
|
|
$ea = $pdo->prepare("INSERT INTO election_assignments (id, election_id, user_id, role_in_election, assigned_by) VALUES (?, ?, ?, ?, ?)");
|
|
$ea->execute([uuid(), $election_id, $user_id, $role_in_election, $_SESSION['user_id']]);
|
|
}
|
|
|
|
audit_log('assigned_officer', 'users', $user_id, null, null, "Assigned $role $name to election $election_id");
|
|
|
|
$pdo->commit();
|
|
header("Location: ../officers_management.php?success=officer_assigned");
|
|
exit;
|
|
} catch (Exception $e) {
|
|
if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
|
|
die("Error: " . $e->getMessage());
|
|
}
|
|
} else {
|
|
header("Location: ../officers_management.php");
|
|
exit;
|
|
}
|