<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'check_duplicates') {
        $semester_id = (int)($_POST['semester_id'] ?? 0);
        $student_ids = json_decode($_POST['student_ids'] ?? '[]', true);
        
        if (empty($semester_id) || empty($student_ids)) {
            echo json_encode([
                'success' => false,
                'message' => 'بيانات غير كافية'
            ]);
            exit;
        }
        
        try {
            $mysqli1->set_charset('utf8mb4');
            
            // Prepare placeholders for IN clause
            $placeholders = str_repeat('?,', count($student_ids) - 1) . '?';
            
            $sql = "
                SELECT r.student_id, r.student_name, r.payment_reference, 
                       r.is_paid, r.created_at
                FROM registrations r
                WHERE r.semester_id = ? 
                AND r.student_id IN ($placeholders)
                AND r.deleted_at IS NULL
            ";
            
            $stmt = $mysqli1->prepare($sql);
            
            // Build parameters array: semester_id + all student_ids
            $params = array_merge([$semester_id], $student_ids);
            
            // Build types string: i for semester_id + s for each student_id
            $types = 'i' . str_repeat('s', count($student_ids));
            
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            $duplicates = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            echo json_encode([
                'success' => true,
                'duplicate_count' => count($duplicates),
                'duplicates' => $duplicates
            ]);
            
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'حدث خطأ: ' . $e->getMessage()
            ]);
        }
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'إجراء غير معروف'
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'طلب غير صالح'
    ]);
}
?>