<?php
// ajax/save_symbol_numbers.php
include('../includes/db.php');


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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log received data
error_log("Save symbol numbers request received");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Check if data is received
    if (!isset($_POST['symbolData']) || !isset($_POST['exam_id'])) {
        echo json_encode([
            'success' => false,
            'message' => 'Required data missing'
        ]);
        exit;
    }
    
    $symbolData = json_decode($_POST['symbolData'], true);
    $examId = intval($_POST['exam_id']);
    
    // Log for debugging
    error_log("Exam ID: $examId");
    error_log("Number of records to save: " . count($symbolData));
    error_log("Sample data: " . json_encode(array_slice($symbolData, 0, 3)));
    
    if (empty($symbolData)) {
        echo json_encode([
            'success' => false,
            'message' => 'No symbol data to save'
        ]);
        exit;
    }
    
    $successCount = 0;
    $errorCount = 0;
    $duplicateCount = 0;
    $errors = [];
    
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        foreach ($symbolData as $index => $data) {
            // Validate required fields
            if (!isset($data['studentId']) || !isset($data['symbolNumber']) || empty($data['symbolNumber'])) {
                $errorCount++;
                $errors[] = "Record $index: Missing student ID or symbol number";
                continue;
            }
            
            $studentId = intval($data['studentId']);
            $classId = isset($data['classId']) ? intval($data['classId']) : 0;
            $symbolNumber = trim($data['symbolNumber']);
            
            // Skip if symbol number is empty
            if (empty($symbolNumber)) {
                $errorCount++;
                $errors[] = "Record $index: Empty symbol number for student ID $studentId";
                continue;
            }
            
            // Validate symbol number format (should be numeric)
            if (!is_numeric($symbolNumber)) {
                $errorCount++;
                $errors[] = "Record $index: Invalid symbol number format for student ID $studentId";
                continue;
            }
            
            // Check if this symbol number is already assigned to another student for this exam
            $checkQuery = "SELECT student_id FROM symbolno_data 
                          WHERE exam_id = ? AND symbol_no = ? AND student_id != ?";
            $checkStmt = $conn->prepare($checkQuery);
            $checkStmt->bind_param("isi", $examId, $symbolNumber, $studentId);
            $checkStmt->execute();
            $checkResult = $checkStmt->get_result();
            
            if ($checkResult->num_rows > 0) {
                $duplicateRow = $checkResult->fetch_assoc();
                $duplicateCount++;
                $errors[] = "Record $index: Symbol number $symbolNumber is already assigned to student ID {$duplicateRow['student_id']}";
                $checkStmt->close();
                continue;
            }
            $checkStmt->close();
            
            // Check if this student already has a symbol number for this exam
            $existingQuery = "SELECT id, symbol_no FROM symbolno_data 
                             WHERE student_id = ? AND exam_id = ?";
            $existingStmt = $conn->prepare($existingQuery);
            $existingStmt->bind_param("ii", $studentId, $examId);
            $existingStmt->execute();
            $existingResult = $existingStmt->get_result();
            
            if ($existingResult->num_rows > 0) {
                // Update existing record
                $existingData = $existingResult->fetch_assoc();
                $oldSymbol = $existingData['symbol_no'];
                
                $updateQuery = "UPDATE symbolno_data 
                               SET symbol_no = ?, class_id = ? 
                               WHERE student_id = ? AND exam_id = ?";
                $updateStmt = $conn->prepare($updateQuery);
                $updateStmt->bind_param("siii", $symbolNumber, $classId, $studentId, $examId);
                
                if ($updateStmt->execute()) {
                    $successCount++;
                    error_log("Updated symbol for student $studentId: $oldSymbol -> $symbolNumber");
                } else {
                    $errorCount++;
                    $errors[] = "Record $index: Failed to update symbol for student ID $studentId: " . $updateStmt->error;
                }
                
                $updateStmt->close();
            } else {
                // Insert new record
                $insertQuery = "INSERT INTO symbolno_data (student_id, class_id, exam_id, symbol_no) 
                               VALUES (?, ?, ?, ?)";
                $insertStmt = $conn->prepare($insertQuery);
                $insertStmt->bind_param("iiis", $studentId, $classId, $examId, $symbolNumber);
                
                if ($insertStmt->execute()) {
                    $successCount++;
                    error_log("Inserted symbol for student $studentId: $symbolNumber");
                } else {
                    $errorCount++;
                    $errors[] = "Record $index: Failed to insert symbol for student ID $studentId: " . $insertStmt->error;
                }
                
                $insertStmt->close();
            }
            
            $existingStmt->close();
        }
        
        // Commit transaction
        $conn->commit();
        
        // Prepare response
        $response = [
            'success' => true,
            'message' => 'Symbol numbers saved successfully!',
            'success_count' => $successCount,
            'error_count' => $errorCount,
            'duplicate_count' => $duplicateCount,
            'total_records' => count($symbolData)
        ];
        
        // Add errors if any
        if (!empty($errors)) {
            $response['errors'] = array_slice($errors, 0, 10); // Limit to first 10 errors
            if (count($errors) > 10) {
                $response['errors'][] = '... and ' . (count($errors) - 10) . ' more errors';
            }
        }
        
        echo json_encode($response);
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        
        error_log("Transaction failed: " . $e->getMessage());
        
        echo json_encode([
            'success' => false,
            'message' => 'Transaction failed: ' . $e->getMessage()
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method. Please use POST.'
    ]);
}

$conn->close();
?>