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

// Load settings (timezone config)
$settingsPath = __DIR__ . '/../../database/login/sessions.json';
$timezone = 'UTC'; // Default fallback

if (file_exists($settingsPath)) {
    $settingsContent = file_get_contents($settingsPath);
    $settings = json_decode($settingsContent, true);
    if (is_array($settings) && !empty($settings['timezone'])) {
        $timezone = $settings['timezone'];
    }
}

// Set PHP's default timezone
date_default_timezone_set($timezone);

// Get raw JSON input
$input = json_decode(file_get_contents("php://input"), true);

if (!$input || !is_array($input)) {
    echo json_encode(["status" => "error", "message" => "Invalid JSON"]);
    exit;
}

// Extract and sanitize session data
$peerId       = $input['peerId'] ?? '';
$sessionEmail = $input['sessionEmail'] ?? '';
$sessionName  = $input['sessionName'] ?? '';
$sessionRole  = $input['sessionRole'] ?? '';
$sessionTime  = $input['sessionTime'] ?? '';
$sessionKey   = $input['sessionKey'] ?? '';

if (empty($peerId)) {
    echo json_encode(["status" => "error", "message" => "Missing peerId"]);
    exit;
}

// Build full session record
$sessionData = [
    'peerId'       => $peerId,
    'sessionEmail' => $sessionEmail,
    'sessionName'  => $sessionName,
    'sessionRole'  => $sessionRole,
    'sessionTime'  => $sessionTime,
    'sessionKey'   => $sessionKey,
    'loggedAt'     => date('Y-m-d H:i:s') // With proper timezone
];

// File path to save
$filePath = __DIR__ . '/../../database/login/sessions.json';

// Create parent directories if not exist
if (!file_exists(dirname($filePath))) {
    mkdir(dirname($filePath), 0777, true);
}

// Load existing sessions if file exists
$existing = [];
if (file_exists($filePath)) {
    $content = file_get_contents($filePath);
    $existing = json_decode($content, true);
    if (!is_array($existing)) $existing = [];
}

// Check if session with same peerId exists
$found = false;
foreach ($existing as &$session) {
    if (isset($session['peerId']) && $session['peerId'] === $peerId) {
        $session = $sessionData; // Update existing session
        $found = true;
        break;
    }
}
unset($session); // Break reference

// If not found, append new session
if (!$found) {
    $existing[] = $sessionData;
}

// Save back to file
if (file_put_contents($filePath, json_encode($existing, JSON_PRETTY_PRINT))) {
    echo json_encode([
        "status" => "success",
        "peerId" => $peerId,
        "message" => $found ? "Session updated" : "Session added",
        "timezoneUsed" => $timezone
    ]);
} else {
    echo json_encode(["status" => "error", "message" => "Failed to save session data"]);
}
