<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    die(json_encode(['success' => false, 'message' => 'User not logged in.']));
}

// Get JSON data from the request
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);

// Check if batch ID is provided
if (!isset($data['batchId']) || !is_numeric($data['batchId'])) {
    die(json_encode(['success' => false, 'message' => 'Invalid batch ID.']));
}

$batchId = intval($data['batchId']);
$userId = $_SESSION['user_id'];

try {
    // Fetch batch information
    $batchStmt = $conn->prepare("
        SELECT * FROM import_batches 
        WHERE batch_id = ? AND created_by = ?
    ");
    
    $batchStmt->bind_param("ii", $batchId, $userId);
    $batchStmt->execute();
    $batchResult = $batchStmt->get_result();
    
    if ($batchResult->num_rows === 0) {
        die(json_encode(['success' => false, 'message' => 'Batch not found or you do not have permission to access it.']));
    }
    
    $batchInfo = $batchResult->fetch_assoc();
    
    // Check if there are any invalid records
    $checkInvalidStmt = $conn->prepare("
        SELECT COUNT(*) as count FROM import_records 
        WHERE batch_id = ? AND status = 'invalid'
    ");
    
    $checkInvalidStmt->bind_param("i", $batchId);
    $checkInvalidStmt->execute();
    $checkResult = $checkInvalidStmt->get_result();
    $row = $checkResult->fetch_assoc();
    
    if ($row['count'] > 0) {
        // There are invalid records, make sure the user wants to proceed
        if (!isset($data['forceProcess']) || !$data['forceProcess']) {
            // Return error and require confirmation to proceed
            die(json_encode([
                'success' => false, 
                'message' => 'There are invalid records in this batch. Please fix them or confirm to continue with valid records only.',
                'requiresConfirmation' => true,
                'invalidCount' => $row['count']
            ]));
        }
    }
    
    // Update batch status to approved for processing
    $updateStmt = $conn->prepare("
        UPDATE import_batches 
        SET status = 'approved' 
        WHERE batch_id = ?
    ");
    
    $updateStmt->bind_param("i", $batchId);
    
    if (!$updateStmt->execute()) {
        // Log error
        error_log("Error updating batch status: " . $updateStmt->error);
        die(json_encode(['success' => false, 'message' => 'Error updating batch status.']));
    }
    
    // Return success
    echo json_encode([
        'success' => true,
        'message' => 'Batch submitted for processing.',
        'batchId' => $batchId,
        'status' => 'approved'
    ]);
    
} catch (Exception $e) {
    // Log the error
    error_log("Error submitting import: " . $e->getMessage());
    
    die(json_encode(['success' => false, 'message' => 'Error submitting import: ' . $e->getMessage()]));
}
?>