<?php
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../includes/access_control.php';
require_once '../includes/branch_helper.php';
require_once __DIR__ . '/encoding_helper.php';

ensure_school_branches_schema($pdo);

class SimplePDFParser {
    public static function convertPDFToCSV($pdf_path) {
        $temp_txt = tempnam(sys_get_temp_dir(), 'pdf_to_txt_');
        
        // Check if exec function is available
        if (!function_exists('exec')) {
            return null; // exec function is disabled
        }
        
        // Check if pdftotext utility exists
        $result = 0;
        $output = [];
        exec('which pdftotext 2>/dev/null || where pdftotext 2>/dev/null', $output, $result);
        if ($result !== 0) {
            // pdftotext not found, try alternative approach
            return null;
        }
        
        $command = 'pdftotext -layout "' . addslashes($pdf_path) . '" "' . addslashes($temp_txt) . '"';
        exec($command, $output, $return_var);
        
        if ($return_var !== 0 || !file_exists($temp_txt)) {
            unlink($temp_txt);
            return null;
        }
        
        $text = file_get_contents($temp_txt);
        $lines = explode("\n", $text);
        
        // Simple heuristic to identify tabular data
        $csv_lines = [];
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line)) continue;
            
            // Look for lines that appear to be table rows (contain multiple words separated by spaces)
            $fields = preg_split('/\s{2,}/', $line); // Split by 2 or more spaces
            if (count($fields) >= 3) { // Likely a table row
                $csv_line = [];
                foreach ($fields as $field) {
                    $csv_line[] = '"' . str_replace('"', '""', trim($field)) . '"';
                }
                $csv_lines[] = implode(',', $csv_line);
            }
        }
        
        unlink($temp_txt);
        
        if (empty($csv_lines)) {
            return null; // No tabular data detected
        }
        
        return implode("\n", $csv_lines);
    }
}

// Check if user is logged in and has appropriate role
// if (!is_logged_in() || !in_array($_SESSION['user_role'], ['admin', 'operator', 'teacher'])) {
//     header('Location: ../login.php');
//     exit();
// }

function convert_to_utf8($value) {
    if (is_string($value)) {
        return EncodingHelper::cleanBengaliText($value);
    }
    return $value;
}

function strip_csv_bom_from_handle($handle) {
    $pos = ftell($handle);
    $bom = fread($handle, 3);
    if ($bom !== "\xEF\xBB\xBF") {
        fseek($handle, $pos);
    }
}

// Function to get class ID by name
function get_class_id_by_name($pdo, $class_name) {
    $stmt = $pdo->prepare("SELECT id FROM classes WHERE name = ? AND status = 'active'");
    $stmt->execute([$class_name]);
    $result = $stmt->fetch();
    return $result ? $result['id'] : false;
}

function get_branch_id_by_value($pdo, $branch_value) {
    $branch_value = trim((string)$branch_value);
    if ($branch_value === '') {
        return null;
    }
    $stmt = $pdo->prepare("
        SELECT id FROM school_branches
        WHERE status = 'active' AND (branch_name = ? OR branch_code = ?)
        LIMIT 1
    ");
    $stmt->execute([$branch_value, strtoupper($branch_value)]);
    $row = $stmt->fetch();
    if ($row) {
        return (int)$row['id'];
    }
    $ins = $pdo->prepare("INSERT INTO school_branches (branch_name, branch_code, status, created_at) VALUES (?, ?, 'active', NOW())");
    $ins->execute([$branch_value, strtoupper($branch_value)]);
    return (int)$pdo->lastInsertId();
}

// Function to create a subject if it doesn't exist
function create_subject_if_not_exists($pdo, $subject_code) {
    // Handle range notation (e.g., 101_102 or 101-102) by using the original code format
    $check_code = $subject_code;
    $display_code = str_replace('_', '-', $check_code); // Convert underscore to dash for comparison
    
    // First check if subject already exists in either format
    $check_stmt = $pdo->prepare("SELECT id FROM subjects WHERE code = ? OR code = ?");
    $check_stmt->execute([$check_code, $display_code]);
    $existing_subject = $check_stmt->fetch();
    
    if ($existing_subject) {
        return $existing_subject['id'];
    }
    
    // Generate a default name for the subject based on the code
    $default_name = "Subject " . $subject_code;
    
    // Insert the new subject with the original code format
    $insert_stmt = $pdo->prepare(
        "INSERT INTO subjects (name, code, description, status, created_at, updated_at) 
         VALUES (?, ?, ?, 'active', NOW(), NOW())"
    );
    $insert_stmt->execute([$default_name, $subject_code, "Auto-created subject with code: $subject_code"]);
    
    // Return the ID of the newly created subject
    return $pdo->lastInsertId();
}

// Function to get subject IDs by codes
function get_subject_ids_by_codes($pdo, $subject_codes_str) {
    if (empty($subject_codes_str)) {
        return [];
    }
    
    // Split by comma to get individual subject codes
    $subject_codes = array_map('trim', explode(',', $subject_codes_str));
    $subject_ids = [];
    
    foreach ($subject_codes as $code) {
        $code = trim($code);
        if (!empty($code)) {
            // Handle range notation (e.g., 101_102)
            $stmt = $pdo->prepare("SELECT id FROM subjects WHERE code = ? OR code = ?");
            $stmt->execute([$code, str_replace('_', '-', $code)]);
            
            $found = false;
            while ($row = $stmt->fetch()) {
                $subject_ids[] = $row['id'];
                $found = true;
            }
            
            // If subject not found, create it automatically
            if (!$found) {
                $new_subject_id = create_subject_if_not_exists($pdo, $code);
                $subject_ids[] = $new_subject_id;
            }
        }
    }
    
    return $subject_ids;
}

// After the function definitions and before the main logic
// Main processing logic
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['student_file'])) {
    $file = $_FILES['student_file'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $error_message = "ফাইল আপলোডে ত্রুটি হয়েছে।";
    } elseif (!in_array(strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)), ['csv', 'pdf'])) {
        $error_message = "শুধুমাত্র CSV বা PDF ফাইল আপলোড করা যাবে।";
    } else {
        $uploaded_file_path = $file['tmp_name'];
                $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                
                // If it's a PDF, convert it to temporary CSV
                if ($file_extension === 'pdf') {
                    $csv_content = SimplePDFParser::convertPDFToCSV($uploaded_file_path);
                    
                    if ($csv_content === null) {
                        $error_message = "PDF ফাইল থেকে ডেটা এক্সট্রাক্ট করতে সমস্যা হয়েছে। শুধুমাত্র CSV ফাইল গ্রহণ করা হবে।";
                    } else {
                        // Create a temporary CSV file
                        $temp_csv_path = tempnam(sys_get_temp_dir(), 'pdf_to_csv_');
                        file_put_contents($temp_csv_path, $csv_content);
                        $file_path = $temp_csv_path;
                    }
                } else {
                    $file_path = $uploaded_file_path;
                }
        
        $total_rows = 0;
        $successful_imports = 0;
        $failed_imports = 0;
        $errors = [];

        // Debug: Log that we're processing
        error_log("Starting CSV processing for file: " . $file['name']);

        EncodingHelper::convertCsvToUtf8($file_path);

        if (($handle = fopen($file_path, "r")) !== FALSE) {
            strip_csv_bom_from_handle($handle);

            $header = fgetcsv($handle);
            if ($header === FALSE) {
                $error_message = "CSV ফাইলটি খালি বা সঠিক ফরম্যাটে নেই।";
                fclose($handle);
            } else {
                $header = array_map(function ($h) {
                    return EncodingHelper::cleanBengaliText(trim((string)$h));
                }, $header);
                $required_headers = [
                    'first_name', 'last_name', 'class_name', 'session',
                    'group_name', 'roll_number', 'subject_codes'
                ];
                // Optional headers (allowed but not required)
                $optional_headers = [
                    'father_name','mother_name','email','phone','address',
                    'date_of_birth','gender','religion','admission_date',
                    'guardian_name','guardian_phone','guardian_email','guardian_address',
                    'branch_name'
                ];

                $missing = array_diff($required_headers, $header);
                if (count($missing) > 0) {
                    $error_message = "CSV ফাইলের হেডার সঠিক নয়। নিচের কলামগুলো পাওয়া যায়নি: " . implode(', ', $missing) . "। টেমপ্লেট ডাউনলোড করে ব্যবহার করুন।";
                    fclose($handle);
                } else {
                    $header_map = array_flip($header);
                    
                    try {
                        $pdo->beginTransaction();
                        
                        while (($data = fgetcsv($handle)) !== FALSE) {
                            $total_rows++;
                            if (count($data) < count($header)) {
                                $errors[] = "Row {$total_rows}: কলাম সংখ্যা কম (মোট: " . count($header) . ", পাওয়া গেছে: " . count($data) . ")।";
                                $failed_imports++;
                                continue;
                            }
                            $row_data = array_map(function($value) {
                                return convert_to_utf8($value);
                            }, $data);

                            $student = [];
                            foreach ($header_map as $key => $index) {
                                $student[$key] = $row_data[$index] ?? null;
                            }

                            // Basic validation
                            $student['first_name'] = trim($student['first_name'] ?? '');
                            $student['class_name'] = trim($student['class_name'] ?? '');
                            $student['session'] = trim($student['session'] ?? '');
                            $student['roll_number'] = trim($student['roll_number'] ?? '');
                            if ($student['first_name'] === '' && $student['class_name'] === '' && $student['session'] === '' && $student['roll_number'] === '') {
                                continue; // skip blank rows
                            }
                            if ($student['first_name'] === '' || $student['class_name'] === '' || $student['session'] === '' || $student['roll_number'] === '') {
                                $failed_imports++;
                                $missing = [];
                                if ($student['first_name'] === '') $missing[] = 'নাম';
                                if ($student['class_name'] === '') $missing[] = 'ক্লাস';
                                if ($student['session'] === '') $missing[] = 'সেশন';
                                if ($student['roll_number'] === '') $missing[] = 'রোল';
                                $errors[] = "Row {$total_rows}: " . implode(', ', $missing) . " ফাঁকা আছে।";
                                continue;
                            }

                            // Get Class ID
                            $class_id = get_class_id_by_name($pdo, $student['class_name']);
                            if (!$class_id) {
                                $failed_imports++;
                                $errors[] = "Row {$total_rows}: ক্লাস ‘{$student['class_name']}’ খুঁজে পাওয়া যায়নি।";
                                continue;
                            }

                            $branch_value = trim($student['branch_name'] ?? '');
                            $branch_id = get_branch_id_by_value($pdo, $branch_value);

                            // Duplicate roll: same class + session + group + branch only
                            $stmt_check = $pdo->prepare("
                                SELECT COUNT(*) FROM students
                                WHERE class_id = ? AND session = ? AND COALESCE(group_name, '') = ?
                                AND roll_number = ? AND status = 'active'
                                AND COALESCE(branch_id, 0) = COALESCE(?, 0)
                            ");
                            $stmt_check->execute([
                                $class_id,
                                $student['session'],
                                $student['group_name'] ?: '',
                                $student['roll_number'],
                                $branch_id
                            ]);
                            if ($stmt_check->fetchColumn() > 0) {
                                $failed_imports++;
                                $branch_note = $branch_value !== '' ? " (শাখা: {$branch_value})" : '';
                                $errors[] = "Row {$total_rows}: রোল ‘{$student['roll_number']}’ এই ক্লাস, সেশন ও শাখায়{$branch_note} ইতিমধ্যে আছে।";
                                continue;
                            }
                            
                            // Generate student ID with collision avoidance
                            $year = date('Y');
                            $attempt = 1;
                            do {
                                $student_id_generated = $year . str_pad($attempt, 4, '0', STR_PAD_LEFT);
                                $stmt_check_id = $pdo->prepare("SELECT COUNT(*) FROM students WHERE student_id = ?");
                                $stmt_check_id->execute([$student_id_generated]);
                                $exists = $stmt_check_id->fetchColumn() > 0;
                                $attempt++;
                                // Safety check to prevent infinite loop
                                if ($attempt > 9999) {
                                    throw new Exception("Unable to generate unique student ID after 9999 attempts");
                                }
                            } while ($exists);

                            // Insert student
                            $stmt_insert = $pdo->prepare("
                                INSERT INTO students (
                                    student_id, first_name, last_name, father_name, mother_name, email, phone, address,
                                    date_of_birth, gender, religion, class_id, branch_id, session, group_name, roll_number, admission_date,
                                    guardian_name, guardian_phone, guardian_email, guardian_address, status
                                ) VALUES (
                                    :student_id, :first_name, :last_name, :father_name, :mother_name, :email, :phone, :address,
                                    :date_of_birth, :gender, :religion, :class_id, :branch_id, :session, :group_name, :roll_number, :admission_date,
                                    :guardian_name, :guardian_phone, :guardian_email, :guardian_address, 'active'
                                )
                            ");
                            
                            $stmt_insert->execute([
                                ':student_id' => $student_id_generated,
                                ':first_name' => $student['first_name'],
                                ':last_name' => $student['last_name'],
                                ':father_name' => $student['father_name'],
                                ':mother_name' => $student['mother_name'],
                                ':email' => $student['email'],
                                ':phone' => $student['phone'],
                                ':address' => $student['address'],
                                ':date_of_birth' => !empty($student['date_of_birth']) ? $student['date_of_birth'] : null,
                                ':gender' => $student['gender'],
                                ':religion' => !empty($student['religion']) ? $student['religion'] : null,
                                ':class_id' => $class_id,
                                ':branch_id' => $branch_id,
                                ':session' => $student['session'],
                                ':group_name' => $student['group_name'],
                                ':roll_number' => $student['roll_number'],
                                ':admission_date' => !empty($student['admission_date']) ? $student['admission_date'] : date('Y-m-d'),
                                ':guardian_name' => $student['guardian_name'],
                                ':guardian_phone' => $student['guardian_phone'],
                                ':guardian_email' => $student['guardian_email'],
                                ':guardian_address' => $student['guardian_address']
                            ]);
                            
                            $student_db_id = $pdo->lastInsertId();

                            // Get and insert subjects
                            $subject_ids = get_subject_ids_by_codes($pdo, $student['subject_codes']);
                            if (!empty($subject_ids)) {
                                $stmt_subj = $pdo->prepare("INSERT INTO student_subjects (student_id, subject_id, is_fourth_subject) VALUES (?, ?, ?)");
                                
                                // Process subjects - mark the last one as fourth subject
                                $subject_count = count($subject_ids);
                                foreach ($subject_ids as $index => $subject_id) {
                                    try {
                                        // Mark the last subject as fourth subject
                                        $is_fourth_subject = ($index == $subject_count - 1) ? 1 : 0;
                                        $stmt_subj->execute([$student_db_id, $subject_id, $is_fourth_subject]);
                                    } catch (PDOException $e) {
                                        // Ignore duplicate subject error
                                        if (isset($e->errorInfo[1]) && $e->errorInfo[1] != 1062) {
                                            throw $e;
                                        }
                                    }
                                }
                                
                                // Also link subjects to class if they aren't already linked
                                foreach ($subject_ids as $subject_id) {
                                    try {
                                        $stmt_class_link = $pdo->prepare("INSERT IGNORE INTO class_subjects (class_id, subject_id, created_at) VALUES (?, ?, NOW())");
                                        $stmt_class_link->execute([$class_id, $subject_id]);
                                    } catch (PDOException $e) {
                                        // Just continue if there's an error linking to class
                                        error_log("Error linking subject $subject_id to class $class_id: " . $e->getMessage());
                                    }
                                }
                            }
                            
                            $successful_imports++;
                        }
                        
                        $pdo->commit();
                        $success_message = "ফাইল সফলভাবে প্রসেস করা হয়েছে। শেষ বিষয়টি চতুর্থ বিষয় হিসাবে চিহ্নিত করা হয়েছে।";
                        
                    } catch (Exception $e) {
                        $pdo->rollBack();
                        $error_message = "ডাটাবেস ত্রুটি: " . $e->getMessage();
                        $failed_imports = $total_rows - $successful_imports;
                    }
                    
                    fclose($handle);
                    
                    $upload_summary = [
                        'total_rows' => $total_rows,
                        'successful_imports' => $successful_imports,
                        'failed_imports' => $failed_imports,
                        'errors' => $errors
                    ];
                }
            }
        } else {
            $error_message = "ফাইলটি খোলা যায়নি।";
        }
    }
}

// Initialize variables if not set during POST processing
if (!isset($error_message)) $error_message = null;
if (!isset($success_message)) $success_message = null;
if (!isset($upload_summary)) $upload_summary = null;

$branch_list = get_active_school_branches($pdo);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ছাত্র + চতুর্থ বিষয় বাল্ক আপলোড</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root{--indigo:#4fc3f7;--teal:#4dd0e1;--green:#66bb6a;--orange:#ffb74d}
        body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0a1929,#11294a);min-height:100vh;color:#e0e0e0;font-size:.82rem}
        .top-bar{background:linear-gradient(135deg,#0d2137,#1a3a5c);padding:8px 20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;box-shadow:0 2px 20px rgba(0,0,0,.4)}
        .top-bar .brand{color:#4fc3f7;font-weight:700;font-size:.9rem;text-decoration:none}
        .top-bar .nav-links{display:flex;gap:8px;flex-wrap:wrap}
        .top-bar .nav-links a{color:rgba(255,255,255,.7);text-decoration:none;font-size:.72rem;padding:4px 10px;border-radius:6px}
        .top-bar .nav-links a:hover{color:#fff;background:rgba(255,255,255,.08)}
        .page-head{padding:10px 0 8px}
        .page-head h4{margin:0;font-size:1rem;font-weight:800;color:#4fc3f7}
        .page-head p{margin:2px 0 0;font-size:.7rem;color:rgba(255,255,255,.45)}
        .grid{display:grid;grid-template-columns:1fr 340px;gap:10px;align-items:start}
        .panel{background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);border-radius:10px;margin-bottom:10px}
        .panel-hd{padding:8px 12px;border-bottom:1px solid rgba(255,255,255,.06);font-size:.8rem;font-weight:700;color:#90caf9}
        .panel-bd{padding:10px 12px}
        .steps{margin:0;padding-left:18px;font-size:.74rem;line-height:1.55;color:rgba(255,255,255,.7)}
        .steps li{margin-bottom:4px}
        .steps code{background:rgba(79,195,247,.12);color:#4fc3f7;padding:1px 5px;border-radius:4px;font-size:.7rem}
        .note-box{background:rgba(21,101,192,.15);border:1px solid rgba(79,195,247,.2);border-radius:8px;padding:8px 10px;font-size:.72rem;color:#90caf9;margin-top:8px}
        .note-box ul{margin:4px 0 0;padding-left:16px}
        .branch-tags{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px}
        .branch-tag{font-size:.66rem;padding:2px 8px;border-radius:8px;background:rgba(179,157,219,.15);color:#ce93d8;border:1px solid rgba(179,157,219,.25)}
        .form-label{font-size:.72rem;font-weight:600;color:#90caf9;margin-bottom:2px}
        .form-control{font-size:.78rem;padding:6px 10px;border-radius:6px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0}
        .form-control:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.12);color:#e0e0e0;background:rgba(0,0,0,.45)}
        .btn-dl,.btn-up{font-size:.76rem;padding:6px 14px;border-radius:6px;font-weight:700;border:none}
        .btn-dl{background:linear-gradient(135deg,#1565c0,#1e88e5);color:#fff;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
        .btn-up{background:linear-gradient(135deg,#2e7d32,#43a047);color:#fff}
        .btn-dl:hover,.btn-up:hover{opacity:.92;color:#fff}
        .alert-compact{font-size:.76rem;border-radius:8px;padding:6px 10px;margin-bottom:8px}
        .alert-success{background:rgba(46,125,50,.2);border:1px solid rgba(46,125,50,.3);color:#a5d6a7}
        .alert-danger{background:rgba(198,40,40,.2);border:1px solid rgba(198,40,40,.3);color:#ef9a9a}
        .stat-row{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:10px}
        .stat-card{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px;text-align:center}
        .stat-card .n{font-size:1.1rem;font-weight:800;color:#fff}
        .stat-card .l{font-size:.66rem;color:rgba(255,255,255,.45)}
        .stat-card.ok .n{color:#81c784}
        .stat-card.bad .n{color:#ef5350}
        .err-box{max-height:220px;overflow:auto;background:rgba(0,0,0,.25);border-radius:8px;padding:8px 10px;font-size:.72rem}
        .err-box ul{margin:0;padding-left:16px;color:#ffcc80}
        @media(max-width:992px){.grid{grid-template-columns:1fr}}
    </style>
</head>
<body>
    <div class="top-bar">
        <a href="../index.php" class="brand"><i class="fas fa-graduation-cap me-1"></i> স্কুল ম্যানেজমেন্ট</a>
        <div class="nav-links">
            <a href="index.php"><i class="fas fa-arrow-left"></i> বাল্ক আপলোড</a>
            <a href="../admin/branches.php"><i class="fas fa-code-branch"></i> শাখা</a>
            <a href="../students/list.php"><i class="fas fa-users"></i> ছাত্র তালিকা</a>
        </div>
    </div>

    <div class="container-fluid px-3 px-md-4 pb-3">
        <div class="page-head">
            <h4><i class="fas fa-file-upload me-1"></i> ছাত্র + চতুর্থ বিষয় বাল্ক আপলোড</h4>
            <p>CSV/PDF থেকে একসাথে ছাত্র ও বিষয় ইম্পোর্ট — শাখা অনুযায়ী রোল নম্বর</p>
        </div>

        <?php if ($error_message): ?><div class="alert-compact alert-danger"><?= htmlspecialchars($error_message) ?></div><?php endif; ?>
        <?php if ($success_message): ?><div class="alert-compact alert-success"><?= htmlspecialchars($success_message) ?></div><?php endif; ?>

        <?php if ($upload_summary): ?>
        <div class="stat-row">
            <div class="stat-card"><div class="n"><?= (int)$upload_summary['total_rows'] ?></div><div class="l">মোট সারি</div></div>
            <div class="stat-card ok"><div class="n"><?= (int)$upload_summary['successful_imports'] ?></div><div class="l">সফল</div></div>
            <div class="stat-card bad"><div class="n"><?= (int)$upload_summary['failed_imports'] ?></div><div class="l">ব্যর্থ</div></div>
        </div>
        <?php if (!empty($upload_summary['errors'])): ?>
        <div class="panel">
            <div class="panel-hd"><i class="fas fa-exclamation-triangle me-1" style="color:#ffb74d"></i>ত্রুটির তালিকা</div>
            <div class="panel-bd err-box"><ul><?php foreach ($upload_summary['errors'] as $err): ?><li><?= htmlspecialchars($err) ?></li><?php endforeach; ?></ul></div>
        </div>
        <?php endif; ?>
        <?php endif; ?>

        <div class="grid">
            <div class="panel">
                <div class="panel-hd"><i class="fas fa-book-open me-1"></i>নির্দেশনা</div>
                <div class="panel-bd">
                    <ol class="steps">
                        <li><strong>টেমপ্লেট ডাউনলোড</strong> করুন (UTF-8 BOM — Excel-এ বাংলা ঠিক দেখাবে)।</li>
                        <li>Excel-এ এডিটের পর <strong>CSV UTF-8 (Comma delimited)</strong> বা <strong>UTF-8 BOM</strong> হিসেবে সেভ করুন।</li>
                        <li>প্রতি ছাত্রের জন্য একটি সারি — <code>subject_codes</code> কমা দিয়ে (যেমন: <code>101,107,265_266</code>)।</li>
                        <li>শেষ বিষয়টি <strong>চতুর্থ বিষয়</strong> হিসেবে সেট হবে।</li>
                        <li><code>class_name</code> — ক্লাসের নাম (যেমন Eight, Nine)।</li>
                        <li><code>session</code> — সেশন (যেমন 2025-26)।</li>
                        <li><code>branch_name</code> — শাখার নাম বা কোড (যেমন মূল শাখা / MAIN)। খালি রাখলে শাখা ছাড়া।</li>
                    </ol>
                    <div class="note-box">
                        <strong><i class="fas fa-info-circle me-1"></i>রোল নম্বর নিয়ম:</strong>
                        <ul>
                            <li>একই ক্লাস + সেশন + গ্রুপ + <strong>শাখা</strong>তে রোল অনন্য হতে হবে</li>
                            <li>শাখা ভিন্ন হলে একই ক্লাস-সেশনে একই রোল থাকতে পারে</li>
                            <li>নতুন বিষয় কোড স্বয়ংক্রিয় তৈরি হবে</li>
                        </ul>
                        <?php if (!empty($branch_list)): ?>
                        <div class="branch-tags">
                            <?php foreach ($branch_list as $b): ?>
                                <span class="branch-tag"><?= htmlspecialchars($b['branch_name']) ?><?= !empty($b['branch_code']) ? ' (' . htmlspecialchars($b['branch_code']) . ')' : '' ?></span>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                        <div class="mt-1"><a href="../admin/branches.php" style="color:#4fc3f7;font-size:.7rem">শাখা যোগ করুন →</a></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div>
                <div class="panel">
                    <div class="panel-hd"><i class="fas fa-download me-1" style="color:var(--teal)"></i>টেমপ্লেট</div>
                    <div class="panel-bd">
                        <a href="download_students_with_subjects_template.php" class="btn-dl w-100 justify-content-center mb-2">
                            <i class="fas fa-file-csv"></i> বাংলা UTF-8 টেমপ্লেট
                        </a>
                        <a href="templates/students_with_subjects_template.csv" class="btn-dl w-100 justify-content-center mb-2" style="background:linear-gradient(135deg,#455a64,#607d8b);font-size:.7rem" download>
                            <i class="fas fa-download"></i> স্ট্যাটিক CSV (বিকল্প)
                        </a>
                        <div style="font-size:.66rem;color:rgba(255,255,255,.4)">বাংলা নাম/ঠিকানা/শাখা সাপোর্টেড · কলাম: first_name, class_name, session, branch_name, roll_number, subject_codes</div>
                    </div>
                </div>
                <div class="panel">
                    <div class="panel-hd"><i class="fas fa-upload me-1" style="color:var(--green)"></i>আপলোড</div>
                    <div class="panel-bd">
                        <form action="" method="post" enctype="multipart/form-data">
                            <div class="mb-2">
                                <label class="form-label" for="student_file">CSV বা PDF ফাইল</label>
                                <input type="file" class="form-control" id="student_file" name="student_file" accept=".csv,.pdf" required>
                            </div>
                            <button type="submit" class="btn-up w-100"><i class="fas fa-upload me-1"></i>আপলোড ও প্রসেস</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>