<?php
declare(strict_types=1);

session_start();
require_once '../../../config.php';

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

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'copied_count' => 0, 'skipped_count' => 0]);
    exit;
}

$conn = getDBConnection();
if (!$conn) {
    echo json_encode(['success' => false, 'copied_count' => 0, 'skipped_count' => 0]);
    exit;
}

$sourceClass = trim((string) ($_POST['source_class'] ?? ''));
$sourceTerm = trim((string) ($_POST['source_term'] ?? ''));
$sourceYear = trim((string) ($_POST['source_year'] ?? ''));
$targetClass = trim((string) ($_POST['target_class'] ?? ''));
$targetTerm = trim((string) ($_POST['target_term'] ?? ''));
$targetYear = trim((string) ($_POST['target_year'] ?? ''));

if ($sourceClass === '' || $sourceTerm === '' || $sourceYear === '' || $targetClass === '' || $targetTerm === '' || $targetYear === '') {
    echo json_encode(['success' => false, 'copied_count' => 0, 'skipped_count' => 0, 'message' => 'All copy fields are required.']);
    exit;
}

$countStmt = $conn->prepare(
    "SELECT COUNT(*) AS total
     FROM timetable_slots
     WHERE class_name = ? AND academic_year = ? AND term = ?"
);
$countStmt->bind_param('sss', $sourceClass, $sourceYear, $sourceTerm);
$countStmt->execute();
$sourceTotal = (int) (($countStmt->get_result()->fetch_assoc()['total'] ?? 0));
$countStmt->close();

$insertStmt = $conn->prepare(
    "INSERT IGNORE INTO timetable_slots
     (class_name, day_of_week, period_id, subject_id, teacher_id, room, academic_year, term)
     SELECT ?, day_of_week, period_id, subject_id, teacher_id, room, ?, ?
     FROM timetable_slots
     WHERE class_name = ? AND academic_year = ? AND term = ?"
);
$insertStmt->bind_param('ssssss', $targetClass, $targetYear, $targetTerm, $sourceClass, $sourceYear, $sourceTerm);
$insertStmt->execute();
$copiedCount = $insertStmt->affected_rows;
$insertStmt->close();

$skippedCount = max(0, $sourceTotal - $copiedCount);

echo json_encode([
    'success' => true,
    'copied_count' => $copiedCount,
    'skipped_count' => $skippedCount,
    'message' => 'Timetable copied successfully.'
]);

