<?php
/**
 * Server Login API
 * Handles server authentication
 */

session_start();
require 'config.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST method allowed', null);
}

$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['employee_id']) || !isset($data['password'])) {
    sendResponse(false, 'Employee ID and password are required', null);
}

$employee_id = $conn->real_escape_string($data['employee_id']);
$password = $data['password'];

// Check if server exists
$sql = "SELECT * FROM servers WHERE employee_id = '" . $employee_id . "' AND status != 'offline'";
$result = $conn->query($sql);

if ($result->num_rows === 0) {
    sendResponse(false, 'Server not found or inactive', null);
}

$server = $result->fetch_assoc();

// Check if password is set
if (empty($server['password'])) {
    sendResponse(false, 'Server account not fully configured. Please contact manager', null);
}

// Verify password
if (!verifyPassword($password, $server['password'])) {
    sendResponse(false, 'Invalid password', null);
}

// Update last login
$update_sql = "UPDATE servers SET is_online = TRUE WHERE id = " . $server['id'];
$conn->query($update_sql);

// Set session variables
$_SESSION['server_id'] = $server['id'];
$_SESSION['server_name'] = $server['name'];
$_SESSION['server_employee_id'] = $server['employee_id'];
$_SESSION['server_phone'] = $server['phone'];
$_SESSION['last_activity'] = time();

// Create response data
$response_data = [
    'id' => $server['id'],
    'name' => $server['name'],
    'employee_id' => $server['employee_id'],
    'phone' => $server['phone']
];

sendResponse(true, 'Login successful', $response_data);
?>
