<?php
// Suppress all error output to ensure clean JSON responses
error_reporting(0);
ini_set('display_errors', 0);
ob_start();

require_once '../../config/config.php';
require_once '../helper/audit_log.php';

// Clean any output buffer and set proper headers
ob_clean();
header('Content-Type: application/json');

try {
    $batch_name = trim($_POST['batch_name'] ?? '');
    $start_year = (int)($_POST['start_year'] ?? 0);
    $end_year = (int)($_POST['end_year'] ?? 0);
    $description = trim($_POST['description'] ?? '');

    // Validation
    $errors = [];
    if ($batch_name === '') { 
        $errors[] = 'Batch name is required.'; 
    }
    if (mb_strlen($batch_name) < 2) { 
        $errors[] = 'Batch name must be at least 2 characters.'; 
    }
    if (mb_strlen($batch_name) > 100) { 
        $errors[] = 'Batch name must not exceed 100 characters.'; 
    }
    if ($start_year < 1900 || $start_year > 2100) {
        $errors[] = 'Start year must be between 1900 and 2100.';
    }
    if ($end_year < 1900 || $end_year > 2100) {
        $errors[] = 'End year must be between 1900 and 2100.';
    }
    if ($start_year >= $end_year) {
        $errors[] = 'End year must be greater than start year.';
    }
    
    if ($errors) { 
        echo json_encode(["status" => "error", "message" => implode(' ', $errors)]); 
        exit; 
    }

    // Check for duplicate batch name
    $check_stmt = $pdo->prepare("SELECT batch_id FROM batches WHERE batch_name = ?");
    $check_stmt->execute([$batch_name]);
    if ($check_stmt->fetch()) {
        echo json_encode(["status" => "error", "message" => "Batch name already exists. Please use a different name."]);
        exit;
    }

    // Insert new batch
    $stmt = $pdo->prepare("INSERT INTO batches (batch_name, start_year, end_year, description) VALUES (?, ?, ?, ?)");
    $stmt->execute([$batch_name, $start_year, $end_year, $description]);
    
    $new_id = $pdo->lastInsertId();
    
    // Write audit log
    write_audit_log($pdo, [
        'module' => 'Academic Structure',
        'action' => 'create',
        'entity_table' => 'batches',
        'entity_id' => $new_id,
        'after_data' => [
            'batch_name' => $batch_name,
            'start_year' => $start_year,
            'end_year' => $end_year,
            'description' => $description
        ],
        'message' => 'Batch created successfully'
    ]);
    
    echo json_encode([
        "status" => "success",
        "message" => "Batch created successfully.",
        "data" => [
            "batch_id" => $new_id,
            "batch_name" => $batch_name,
            "start_year" => $start_year,
            "end_year" => $end_year,
            "description" => $description
        ]
    ]);
    
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        "status" => "error",
        "message" => "An error occurred while creating the batch. Please try again."
    ]);
}
?>










