<?php
// ajax/log_import.php
session_start();
require_once '../layouts/dbconn.php';
require_once '../layouts/session.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false]);
    exit();
}

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

try {
    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    $logData = json_encode([
        'imported' => $input['imported'] ?? 0,
        'skipped' => $input['skipped'] ?? 0,
        'errors' => $input['errors'] ?? 0,
        'filename' => $input['filename'] ?? 'unknown'
    ]);
    
    $stmt = $conn->prepare("
        INSERT INTO activity_log (user_id, action, module, record_type, new_values, ip_address, logged_at)
        VALUES (?, 'IMPORT', 'PATIENTS', 'PATIENT_IMPORT', ?, ?, NOW())
    ");
    
    $stmt->bind_param("iss", $_SESSION['user_id'], $logData, $ipAddress);
    $stmt->execute();
    $stmt->close();
    
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>