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

// Read JSON input
$data = json_decode(file_get_contents('php://input'), true);

if (!$data) {
    echo json_encode(['success' => false, 'error' => 'Invalid input data']);
    exit;
}

$exam_id = isset($data['exam_id']) ? intval($data['exam_id']) : 0;
$class_id = isset($data['class_id']) ? intval($data['class_id']) : 0;
$section_ids = isset($data['section_ids']) ? explode(',', $data['section_ids']) : [];
$symbols = isset($data['symbols']) ? $data['symbols'] : [];

// Validate input
if (!$exam_id || !$class_id || empty($section_ids) || empty($symbols)) {
    echo json_encode(['success' => false, 'error' => 'Missing required data']);
    exit;
}

// Check if exam exists
$exam_check = $conn->prepare("SELECT id FROM examination_type WHERE id = ?");
$exam_check->bind_param("i", $exam_id);
$exam_check->execute();
$exam_result = $exam_check->get_result();
if ($exam_result->num_rows === 0) {
    echo json_encode(['success' => false, 'error' => 'Invalid exam selected']);
    exit;
}
$exam_check->close();

// Check if class exists
$class_check = $conn->prepare("SELECT class_id FROM classes WHERE class_id = ?");
$class_check->bind_param("i", $class_id);
$class_check->execute();
$class_result = $class_check->get_result();
if ($class_result->num_rows === 0) {
    echo json_encode(['success' => false, 'error' => 'Invalid class selected']);
    exit;
}
$class_check->close();

$success_count = 0;
$error_count = 0;
$errors = [];

// Begin transaction
$conn->begin_transaction();

try {
    foreach ($symbols as $item) {
        $student_id = isset($item['student_id']) ? intval($item['student_id']) : 0;
        $symbol_no = isset($item['symbol_no']) ? trim($item['symbol_no']) : '';
        
        if (!$student_id || empty($symbol_no)) {
            $error_count++;
            continue;
        }
        
        // Validate student exists and belongs to selected class/sections
        $student_check = $conn->prepare("SELECT student_id FROM students WHERE student_id = ? AND Class_id = ?");
        $student_check->bind_param("ii", $student_id, $class_id);
        $student_check->execute();
        $student_result = $student_check->get_result();
        
        if ($student_result->num_rows === 0) {
            $student_check->close();
            $error_count++;
            continue;
        }
        $student_check->close();
        
        // Check for duplicate symbol number in this exam
        $duplicate_check = $conn->prepare("SELECT student_id FROM symbolno_data WHERE exam_id = ? AND symbol_no = ? AND student_id != ?");
        $duplicate_check->bind_param("isi", $exam_id, $symbol_no, $student_id);
        $duplicate_check->execute();
        $duplicate_result = $duplicate_check->get_result();
        
        if ($duplicate_result->num_rows > 0) {
            $errors[] = "Symbol number $symbol_no is already assigned to another student";
            $duplicate_check->close();
            $error_count++;
            continue;
        }
        $duplicate_check->close();
        
        // Insert or update symbol number
        $query = "INSERT INTO symbolno_data (student_id, class_id, exam_id, symbol_no) 
                  VALUES (?, ?, ?, ?)
                  ON DUPLICATE KEY UPDATE symbol_no = ?";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("iiiss", $student_id, $class_id, $exam_id, $symbol_no, $symbol_no);
        
        if ($stmt->execute()) {
            $success_count++;
        } else {
            $error_count++;
            $errors[] = "Failed to save symbol for student ID $student_id: " . $stmt->error;
        }
        $stmt->close();
    }
    
    // Update students table with symbol numbers
    foreach ($symbols as $item) {
        $student_id = isset($item['student_id']) ? intval($item['student_id']) : 0;
        $symbol_no = isset($item['symbol_no']) ? trim($item['symbol_no']) : '';
        
        if ($student_id && $symbol_no) {
            $update_student = $conn->prepare("UPDATE students SET symbol_no = ? WHERE student_id = ?");
            $update_student->bind_param("si", $symbol_no, $student_id);
            $update_student->execute();
            $update_student->close();
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    $message = "Symbol numbers saved successfully.<br>";
    $message .= "Successfully saved: $success_count records<br>";
    if ($error_count > 0) {
        $message .= "Failed to save: $error_count records";
    }
    
    echo json_encode([
        'success' => true,
        'message' => $message,
        'saved' => $success_count,
        'failed' => $error_count,
        'errors' => $errors
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    echo json_encode([
        'success' => false,
        'error' => 'Transaction failed: ' . $e->getMessage()
    ]);
}
?>