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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

require_once '../../../config.php';
$conn = getDBConnection();

if (!$conn) {
    echo json_encode([
        'success' => false,
        'message' => 'Database connection failed'
    ]);
    exit;
}

$fromClass = trim($_POST['from_class'] ?? ($_POST['source_class'] ?? ''));
$toClass = trim($_POST['to_class'] ?? ($_POST['target_class'] ?? ''));
$fromTerm = trim($_POST['from_term'] ?? ($_POST['term'] ?? ''));
$toTerm = trim($_POST['to_term'] ?? ($_POST['term'] ?? ''));
$fromYear = trim($_POST['from_year'] ?? ($_POST['academic_year'] ?? getAcademicYear()));
$toYear = trim($_POST['to_year'] ?? ($_POST['academic_year'] ?? getAcademicYear()));

if ($fromClass === '' || $toClass === '' || $fromTerm === '' || $toTerm === '' || $fromYear === '' || $toYear === '') {
    echo json_encode([
        'success' => false,
        'message' => 'Missing required parameters'
    ]);
    exit;
}

$select = $conn->prepare(
    "SELECT subject_id, teacher_id, class_score_percent, exam_score_percent,
            max_class_score, max_exam_score, is_compulsory, display_order
     FROM class_subjects
     WHERE class_name = ? AND term = ? AND academic_year = ?"
);
$select->bind_param('sss', $fromClass, $fromTerm, $fromYear);
$select->execute();
$result = $select->get_result();

$insert = $conn->prepare(
    "INSERT IGNORE INTO class_subjects (
        class_name, subject_id, academic_year, term, teacher_id,
        class_score_percent, exam_score_percent, max_class_score,
        max_exam_score, is_compulsory, display_order
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);

$copied = 0;
while ($row = $result->fetch_assoc()) {
    $insert->bind_param(
        'sissiiddssi',
        $toClass,
        $row['subject_id'],
        $toYear,
        $toTerm,
        $row['teacher_id'],
        $row['class_score_percent'],
        $row['exam_score_percent'],
        $row['max_class_score'],
        $row['max_exam_score'],
        $row['is_compulsory'],
        $row['display_order']
    );
    if ($insert->execute()) {
        $copied += $insert->affected_rows;
    }
}

$insert->close();
$select->close();
$conn->close();

echo json_encode([
    'success' => true,
    'copied' => $copied
]);
?>
