<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include_once 'config/database.php';

// Create upload_logs table if it doesn't exist
$database = new Database();
$db = $database->getConnection();

// Check if upload_logs table exists, create if not
$checkTable = $db->query("SHOW TABLES LIKE 'upload_logs'");
if ($checkTable->rowCount() == 0) {
    $createTable = "
        CREATE TABLE upload_logs (
            id INT(11) AUTO_INCREMENT PRIMARY KEY,
            filename VARCHAR(255) NOT NULL,
            records_processed INT(11) NOT NULL,
            inserted_count INT(11) NOT NULL,
            updated_count INT(11) NOT NULL,
            error_count INT(11) NOT NULL,
            status ENUM('success', 'partial', 'failed') NOT NULL,
            upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ";
    $db->exec($createTable);
}

$query = "SELECT * FROM upload_logs ORDER BY upload_date DESC LIMIT 10";
$stmt = $db->prepare($query);
$stmt->execute();

$uploads = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $uploads[] = [
        'filename' => $row['filename'],
        'records_processed' => $row['records_processed'],
        'inserted_count' => $row['inserted_count'],
        'updated_count' => $row['updated_count'],
        'error_count' => $row['error_count'],
        'status' => $row['status'],
        'upload_date' => date('Y-m-d H:i', strtotime($row['upload_date']))
    ];
}

echo json_encode(['uploads' => $uploads]);
?>