'Invalid input or terms not accepted'], 400); } // Check if user exists $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?"); $stmt->execute([$email]); if ($stmt->fetch()) { jsonResponse(['error' => 'Email already exists'], 409); } $hashedPassword = password_hash($password, PASSWORD_DEFAULT); try { $pdo->beginTransaction(); $stmt = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, ?)"); $stmt->execute([$email, $hashedPassword, $role]); $userId = $pdo->lastInsertId(); // Create empty profile based on role if ($role === 'talent') { $stmt = $pdo->prepare("INSERT INTO talent_profiles (user_id) VALUES (?)"); $stmt->execute([$userId]); } else { $stmt = $pdo->prepare("INSERT INTO producer_profiles (user_id) VALUES (?)"); $stmt->execute([$userId]); } $pdo->commit(); jsonResponse(['message' => 'User registered successfully']); } catch (Exception $e) { $pdo->rollBack(); jsonResponse(['error' => 'Registration failed'], 500); } } elseif ($action === 'login') { $email = $data['email'] ?? ''; $password = $data['password'] ?? ''; $stmt = $pdo->prepare("SELECT id, password, role FROM users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch(); if ($user && password_verify($password, $user['password'])) { $_SESSION['user_id'] = $user['id']; $_SESSION['role'] = $user['role']; writeLog("Login SUCCESS for: $email | Role: " . $user['role']); jsonResponse(['message' => 'Login successful', 'role' => $user['role']]); } else { $reason = !$user ? "User not found" : "Password mismatch"; writeLog("Login FAILED for: $email | Reason: $reason"); if ($user) { // Debug: Log the hash found to see if it matches what we expect writeLog("Hash found in DB: " . $user['password']); } jsonResponse(['error' => 'Invalid credentials'], 401); } } elseif ($action === 'logout') { session_destroy(); jsonResponse(['message' => 'Logged out']); } } elseif ($method === 'GET') { if ($action === 'check') { if (isset($_SESSION['user_id'])) { jsonResponse(['authenticated' => true, 'role' => $_SESSION['role'], 'user_id' => $_SESSION['user_id']]); } else { jsonResponse(['authenticated' => false]); } } } jsonResponse(['error' => 'Invalid request'], 400); ?>