60 lines
1.8 KiB
PHP
60 lines
1.8 KiB
PHP
<?php
|
|
session_start();
|
|
require_once __DIR__ . '/db/config.php';
|
|
|
|
function login($email, $password) {
|
|
try {
|
|
$stmt = db()->prepare("SELECT * FROM users WHERE email = ?");
|
|
$stmt->execute([$email]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user && password_verify($password, $user['password'])) {
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['hospital_id'] = $user['hospital_id'];
|
|
$_SESSION['user_name'] = $user['name'];
|
|
$_SESSION['user_role'] = $user['role'];
|
|
|
|
// Set online status
|
|
$update = db()->prepare("UPDATE users SET online_status = 1 WHERE id = ?");
|
|
$update->execute([$user['id']]);
|
|
|
|
return ['success' => true, 'user' => $user];
|
|
} else {
|
|
return ['success' => false, 'error' => 'Invalid email or password.'];
|
|
}
|
|
} catch (PDOException $e) {
|
|
return ['success' => false, 'error' => 'System error. Please try again later.'];
|
|
}
|
|
}
|
|
|
|
function logout() {
|
|
if (isset($_SESSION['user_id'])) {
|
|
try {
|
|
$update = db()->prepare("UPDATE users SET online_status = 0 WHERE id = ?");
|
|
$update->execute([$_SESSION['user_id']]);
|
|
} catch (PDOException $e) {
|
|
// Log error but continue logout
|
|
}
|
|
}
|
|
session_destroy();
|
|
header("Location: index.php");
|
|
exit;
|
|
}
|
|
|
|
// Handle POST requests
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
header('Content-Type: application/json');
|
|
$action = $_POST['action'] ?? '';
|
|
|
|
if ($action === 'login') {
|
|
$email = trim($_POST['email'] ?? '');
|
|
$password = $_POST['password'] ?? '';
|
|
$result = login($email, $password);
|
|
echo json_encode($result);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
|
|
logout();
|
|
} |