<?php
header('Content-Type: application/json');
require '../../config/db.php';

try {
    // DataTables-style parameters
    $start = isset($_GET['start']) ? (int) $_GET['start'] : 0;
    $length = isset($_GET['length']) ? (int) $_GET['length'] : 10;
    $searchValue = isset($_GET['search']['value']) ? trim($_GET['search']['value']) : '';

    if ($length <= 0) {
        $length = 10;
    }

    // Base query
    $baseSql = "FROM tbl_bulkupload_jobs WHERE 1=1";
    $params = [];

    $jobId = isset($_GET['job_id']) ? (int) $_GET['job_id'] : 0;
    if ($jobId > 0) {
        $stmt = $pdo->prepare("SELECT id, filename, status, total_records, success_count, failure_count, result_file, created_at FROM tbl_bulkupload_jobs WHERE id = :id");
        $stmt->execute([':id' => $jobId]);
        $job = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode(['status' => 'success', 'data' => $job]);
        exit;
    }

    // Simple search on filename, status, id
    if ($searchValue !== '') {
        $baseSql .= " AND (filename LIKE :search OR status LIKE :search OR id LIKE :search)";
        $params[':search'] = '%' . $searchValue . '%';
    }


    // Count total (filtered) records
    $countSql = "SELECT COUNT(*) " . $baseSql;
    $countStmt = $pdo->prepare($countSql);
    foreach ($params as $key => $val) {
        $countStmt->bindValue($key, $val);
    }
    $countStmt->execute();
    $totalRecords = (int) $countStmt->fetchColumn();

    // Fetch page of data
    $dataSql = "SELECT 
                    id,
                    filename,
                    status,
                    total_records,
                    success_count,
                    failure_count,
                    result_file,
                    created_at
                " . $baseSql . " 
                ORDER BY created_at DESC, id DESC
                LIMIT :start, :length";

    $stmt = $pdo->prepare($dataSql);
    foreach ($params as $key => $val) {
        $stmt->bindValue($key, $val);
    }
    $stmt->bindValue(':start', $start, PDO::PARAM_INT);
    $stmt->bindValue(':length', $length, PDO::PARAM_INT);
    $stmt->execute();

    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'draw' => (int) ($_GET['draw'] ?? 1),
        'recordsTotal' => $totalRecords,
        'recordsFiltered' => $totalRecords,
        'data' => $data,
        'status' => 'success'
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error',
        'recordsTotal' => 0,
        'recordsFiltered' => 0,
        'data' => []
    ]);
}
?>