<?php
session_start();
require_once '../config/database.php';
require_once 'encoding_helper.php';

// Only admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';
$upload_results = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['csv_file'])) {
    if ($_FILES['csv_file']['error'] == 0) {
        $file_tmp = $_FILES['csv_file']['tmp_name'];

        // Convert/ensure UTF-8 for Bengali support
        EncodingHelper::convertCsvToUtf8($file_tmp);

        try {
            $handle = fopen($file_tmp, 'r');
            if ($handle !== FALSE) {
                // Read header
                $header = fgetcsv($handle, 0, ',', '"', '"');

                $row_count = 0;
                $success_count = 0;
                $error_count = 0;

                $pdo->beginTransaction();

                while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
                    // Clean encoding
                    $data = array_map(function($item) {
                        if (!mb_check_encoding($item, 'UTF-8')) {
                            return mb_convert_encoding($item, 'UTF-8', 'auto');
                        }
                        return $item;
                    }, $data);

                    $row_count++;

                    try {
                        // Expected columns: name, code, short_name, type, credits, status, description
                        $name = isset($data[0]) ? trim($data[0]) : '';
                        $code = isset($data[1]) ? trim($data[1]) : '';
                        $short_name = isset($data[2]) ? trim($data[2]) : '';
                        $type = isset($data[3]) ? trim($data[3]) : '';
                        $credits = isset($data[4]) ? trim($data[4]) : '';
                        $status = isset($data[5]) ? trim($data[5]) : 'active';
                        $description = isset($data[6]) ? trim($data[6]) : '';

                        if (empty($name) || empty($code)) {
                            throw new Exception("Row $row_count: নাম এবং কোড আবশ্যক");
                        }

                        // Check duplicates by code or name
                        $stmt = $pdo->prepare("SELECT id FROM subjects WHERE code = ? OR name = ?");
                        $stmt->execute([$code, $name]);
                        if ($stmt->fetch()) {
                            throw new Exception("Row $row_count: বিষয় (code/name) ইতিমধ্যে বিদ্যমান: $code / $name");
                        }

                        // Insert subject
                        $stmt = $pdo->prepare("INSERT INTO subjects (name, code, short_name, type, credits, description, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
                        $stmt->execute([$name, $code, $short_name, $type, $credits, $description, $status]);

                        $success_count++;
                        $upload_results[] = [
                            'row' => $row_count,
                            'status' => 'success',
                            'name' => $name,
                            'code' => $code
                        ];

                    } catch (Exception $e) {
                        $error_count++;
                        $upload_results[] = [
                            'row' => $row_count,
                            'status' => 'error',
                            'message' => $e->getMessage()
                        ];
                    }
                }

                fclose($handle);

                if ($error_count == 0) {
                    $pdo->commit();
                    $success_message = "সফলভাবে $success_count টি বিষয় যোগ করা হয়েছে";
                } else {
                    $pdo->rollBack();
                    $error_message = "মোট $row_count টি রো থেকে $error_count টিতে ত্রুটি - কোন ডেটা যোগ করা হয়নি";
                }
            } else {
                $error_message = 'ফাইল পড়তে সমস্যা হয়েছে';
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'ডাটাবেস ত্রুটি: ' . $e->getMessage();
        }
    } else {
        $error_message = 'ফাইল আপলোড করতে সমস্যা হয়েছে';
    }
}
?>

<!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="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php"><i class="fas fa-arrow-left"></i> বাল্ক আপলোড হোম</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-3">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-book"></i> বিষয় আপলোড</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            <a href="templates/subjects_template.csv" class="btn btn-success"><i class="fas fa-download"></i> টেমপ্লেট ডাউনলোড</a>
                            <a href="index.php" class="btn btn-outline-primary"><i class="fas fa-home"></i> হোম</a>
                        </div>
                        <hr>
                        <div class="alert alert-info small">
                            <ol class="mb-0">
                                <li>টেমপ্লেট ডাউনলোড করুন</li>
                                <li>Excel/CSV এ তথ্য পূরণ করুন</li>
                                <li>CSV হিসেবে সেভ করুন (UTF-8/BOM)</li>
                                <li>ফাইল আপলোড করুন</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-9">
                <div class="card">
                    <div class="card-header"><h4><i class="fas fa-upload"></i> বিষয় বাল্ক আপলোড</h4></div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success"><?php echo $success_message; ?></div>
                        <?php endif; ?>
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger"><?php echo $error_message; ?></div>
                        <?php endif; ?>

                        <form method="POST" action="" enctype="multipart/form-data" class="needs-validation" novalidate>
                            <div class="mb-3">
                                <label for="csv_file" class="form-label">CSV ফাইল নির্বাচন করুন <span class="text-danger">*</span></label>
                                <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv" required>
                                <div class="invalid-feedback">অনুগ্রহ করে একটি CSV ফাইল নির্বাচন করুন</div>
                            </div>

                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <a href="index.php" class="btn btn-secondary"><i class="fas fa-times"></i> বাতিল</a>
                                <button type="submit" class="btn btn-success"><i class="fas fa-upload"></i> আপলোড করুন</button>
                            </div>
                        </form>
                    </div>
                </div>

                <?php if (!empty($upload_results)): ?>
                <div class="card mt-4">
                    <div class="card-header"><h5><i class="fas fa-list"></i> আপলোড ফলাফল</h5></div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr><th>রো</th><th>স্ট্যাটাস</th><th>বিবরণ</th></tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($upload_results as $result): ?>
                                        <tr>
                                            <td><?php echo $result['row']; ?></td>
                                            <td><?php echo $result['status'] == 'success' ? '<span class="badge bg-success">সফল</span>' : '<span class="badge bg-danger">ব্যর্থ</span>'; ?></td>
                                            <td>
                                                <?php if ($result['status'] == 'success') echo htmlspecialchars($result['name']) . ' (' . htmlspecialchars($result['code']) . ')'; else echo htmlspecialchars($result['message']); ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="card mt-4">
                    <div class="card-header"><h5><i class="fas fa-table"></i> CSV ফরম্যাট গাইড</h5></div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm">
                                <thead class="table-dark"><tr><th>কলাম</th><th>ফিল্ড</th><th>আবশ্যক</th><th>উদাহরণ</th></tr></thead>
                                <tbody>
                                    <tr><td>A</td><td>Name</td><td class="text-danger">হ্যাঁ</td><td>ইংরেজি/বাংলা নাম</td></tr>
                                    <tr><td>B</td><td>Code</td><td class="text-danger">হ্যাঁ</td><td>ENG101</td></tr>
                                    <tr><td>C</td><td>Short Name</td><td class="text-success">না</td><td>Eng</td></tr>
                                    <tr><td>D</td><td>Type</td><td class="text-success">না</td><td>Optional/Compulsory</td></tr>
                                    <tr><td>E</td><td>Credits</td><td class="text-success">না</td><td>1.0</td></tr>
                                    <tr><td>F</td><td>Status</td><td class="text-success">না</td><td>active/inactive</td></tr>
                                    <tr><td>G</td><td>Description</td><td class="text-success">না</td><td>বিষয় বর্ণনা</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        (function() {
            'use strict';
            window.addEventListener('load', function() {
                var forms = document.getElementsByClassName('needs-validation');
                var validation = Array.prototype.filter.call(forms, function(form) {
                    form.addEventListener('submit', function(event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
    </script>
</body>
</html>
