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

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

// Enable CORS if needed
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Debug logging
error_log("generate_student_id.php called with POST data: " . print_r($_POST, true));

// Check if all required parameters are provided
$required_params = ['college_id', 'program_id', 'section_id', 'batch_id'];
foreach ($required_params as $param) {
    if (!isset($_POST[$param]) || empty($_POST[$param])) {
        error_log("Missing parameter: $param");
        echo json_encode([
            'success' => false,
            'message' => 'جميع الحقول مطلوبة: ' . $param . ' مفقود'
        ]);
        exit;
    }
}

$collegeId = (int)$_POST['college_id'];
$programId = (int)$_POST['program_id'];
$sectionId = (int)$_POST['section_id'];
$batchId = (int)$_POST['batch_id'];

error_log("Processing: college=$collegeId, program=$programId, section=$sectionId, batch=$batchId");

try {
    // Get section code
    $sectionStmt = $mysqli1->prepare("SELECT code FROM sections WHERE id = ?");
    if (!$sectionStmt) {
        throw new Exception("Section prepare failed: " . $mysqli1->error);
    }
    $sectionStmt->bind_param("i", $sectionId);
    $sectionStmt->execute();
    $sectionResult = $sectionStmt->get_result();
    $sectionData = $sectionResult->fetch_assoc();
    $sectionCode = $sectionData['code'] ?? 'SEC';
    
    error_log("Section code: $sectionCode");

    // Get batch code
    $batchStmt = $mysqli1->prepare("SELECT code FROM batches WHERE id = ?");
    if (!$batchStmt) {
        throw new Exception("Batch prepare failed: " . $mysqli1->error);
    }
    $batchStmt->bind_param("i", $batchId);
    $batchStmt->execute();
    $batchResult = $batchStmt->get_result();
    $batchData = $batchResult->fetch_assoc();
    $batchCode = $batchData['code'] ?? 'BAT';
    
    error_log("Batch code: $batchCode");

    // Count existing students with same college, program, section, and batch
    $countStmt = $mysqli1->prepare("
        SELECT COUNT(*) as student_count 
        FROM students 
        WHERE college_id = ? 
        AND program_id = ? 
        AND section_id = ? 
        AND batch_id = ?
        AND deleted_at IS NULL
    ");
    
    if (!$countStmt) {
        throw new Exception("Count prepare failed: " . $mysqli1->error);
    }
    
    $countStmt->bind_param("iiii", $collegeId, $programId, $sectionId, $batchId);
    $countStmt->execute();
    $countResult = $countStmt->get_result();
    $countData = $countResult->fetch_assoc();
    $existingCount = $countData['student_count'] ?? 0;
    
    error_log("Existing count: $existingCount");

    // Calculate next number
    $nextNumber = $existingCount + 1;

    // Pad with leading zeros (3 digits for up to 999 students)
    $nextNumberPadded = str_pad($nextNumber, 3, '0', STR_PAD_LEFT);

    // Generate student ID: section.code + batch.code + padded number
    $nextStudentId = $sectionCode . $batchCode . $nextNumberPadded;
    
    error_log("Generated ID: $nextStudentId");

    // Return the next student ID with format info
    echo json_encode([
        'success' => true,
        'next_student_id' => $nextStudentId,
        'existing_count' => $existingCount,
        'next_number' => $nextNumber,
        'format_info' => 'تنسيق الرقم: ' . $sectionCode . ' (القسم) + ' . $batchCode . ' (الدفعة) + ' . $nextNumberPadded . ' (الرقم التسلسلي)',
        'details' => [
            'section_code' => $sectionCode,
            'batch_code' => $batchCode,
            'padded_number' => $nextNumberPadded
        ]
    ]);

} catch (Exception $e) {
    error_log("Error in generate_student_id.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'خطأ في الخادم: ' . $e->getMessage()
    ]);
    exit;
}
?>