<?php
session_start();
include '../../includes/db_connection.php';

date_default_timezone_set('Asia/Dhaka');

if (!isset($_SESSION['user_id'])) {
    header("Location: /school_management/public/index.php");
    exit();
}

$message = '';
$error = '';

$categories_sql = "SELECT category_id, category_name FROM income_categories";
$categories_result = $conn->query($categories_sql);
$categories = [];
while ($row = $categories_result->fetch_assoc()) {
    $categories[$row['category_name']] = $row['category_id'];
}
$monthly_fee_id = $categories['মাসিক ফি'] ?? null;
$admission_fee_id = $categories['ভর্তি ফি'] ?? null;
$residential_fee_id = $categories['আবাসিক ফি'] ?? null;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $student_id = $_POST['student_id'] ?? '';
    $fee_month = $_POST['fee_month'] ?? null;
    $amount = $_POST['amount'] ?? 0;
    $payment_method = $_POST['payment_method'] ?? '';
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
    $category_id = $_POST['category_id'] ?? 0;
    // ✅ নতুন যোগ: মেমো নং গ্রহণ
    $memo_no = $_POST['memo_no'] ?? ''; 

    if (empty($student_id) && !empty($_POST['student_id_dropdown'])) {
        $student_id = $_POST['student_id_dropdown'];
    }

    $can_proceed = true;
    
    // মাস ও আবাসিক ফি চেক
    if ($category_id == $monthly_fee_id || $category_id == $residential_fee_id) {
        $check_sql = "SELECT COUNT(*) FROM fees WHERE student_id = ? AND fee_month = ? AND category_id = ?";
        $stmt_check = $conn->prepare($check_sql);
        if (!$stmt_check) {
            $error = "SQL Prepare Error (Check 1): " . $conn->error;
            $can_proceed = false;
        } else {
            $stmt_check->bind_param("isi", $student_id, $fee_month, $category_id);
            $stmt_check->execute();
            $stmt_check->bind_result($count);
            $stmt_check->fetch();
            $stmt_check->close();
            if ($count > 0) {
                $error = "এই শিক্ষার্থী ও মাসের জন্য এই ফিটি ইতিমধ্যে জমা করা হয়েছে।";
                $can_proceed = false;
            }
        }
    } 
    // ভর্তি ফি চেক
    elseif ($category_id == $admission_fee_id) {
        $check_sql = "SELECT COUNT(*) FROM fees WHERE student_id = ? AND category_id = ?";
        $stmt_check = $conn->prepare($check_sql);
        if (!$stmt_check) {
            $error = "SQL Prepare Error (Check 2): " . $conn->error;
            $can_proceed = false;
        } else {
            $stmt_check->bind_param("ii", $student_id, $category_id);
            $stmt_check->execute();
            $stmt_check->bind_result($count);
            $stmt_check->fetch();
            $stmt_check->close();
            if ($count > 0) {
                $error = "এই শিক্ষার্থী থেকে ভর্তি ফি ইতিমধ্যে নেওয়া হয়েছে।";
                $can_proceed = false;
            }
        }
    }
    
    // চূড়ান্ত ইনসার্ট লজিক
    if ($can_proceed) {
        // ✅ SQL ক্যোয়ারিতে memo_no কলাম যোগ করা হলো
        $sql = "INSERT INTO fees (student_id, memo_no, fee_month, amount, payment_date, payment_method, category_id) VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        
        if ($stmt === false) {
            $error = "SQL কোয়েরি তৈরিতে সমস্যা: " . $conn->error;
        } else {
            if (!($category_id == $monthly_fee_id || $category_id == $residential_fee_id)) {
                $fee_month = null; // অন্যান্য ফির জন্য মাস দরকার নেই
            }
            
            // ✅ bind_param-এ memo_no এর জন্য একটি 's' যোগ করা হলো
            // i=student_id, s=memo_no, s=fee_month, d=amount, s=payment_date, s=payment_method, i=category_id
            $stmt->bind_param("issdssi", $student_id, $memo_no, $fee_month, $amount, $payment_date, $payment_method, $category_id);

            if ($stmt->execute()) {
                $message = "ফি সফলভাবে সংগ্রহ করা হয়েছে! মেমো নং: " . htmlspecialchars($memo_no);
            } else {
                $error = "সমস্যা: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

// Fetch all classes
$classes_sql = "SELECT class_id, class_name FROM classes ORDER BY class_name";
$classes_result = $conn->query($classes_sql);

?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ফি সংগ্রহ</title>
    <link rel="stylesheet" href="/school_management/public/css/style.css">
    <style>
        .form-container {
            width: 500px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .form-container h2 {
            text-align: center;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group select, .form-group input, .form-group textarea {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .form-buttons {
            text-align: center;
        }
        .form-buttons button, .form-buttons a {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            border: none;
            border-radius: 5px;
            color: white;
            background-color: #28a745;
            transition: background-color 0.3s;
            text-decoration: none;
            display: inline-block;
            margin: 0 5px;
        }
        .form-buttons button:hover, .form-buttons a:hover {
            background-color: #218838;
        }
        .message-success {
            color: green;
            text-align: center;
            font-weight: bold;
        }
        .message-error {
            color: red;
            text-align: center;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div class="header">
    <h1>স্কুল ম্যানেজমেন্ট সিস্টেম</h1>
    <div class="nav">
        <a href="/school_management/public/dashboard.php">ড্যাশবোর্ড</a>
        <a href="/school_management/public/students/students_list.php">শিক্ষার্থী</a>
        <a href="/school_management/public/teachers/teachers_list.php">শিক্ষক</a>
        <a href="/school_management/public/fees/fee_collection.php">ফি সংগ্রহ</a>
        <a href="/school_management/public/subjects/subjects_list.php">বিষয়সমূহ</a>
        <a href="/school_management/public/classes/classes_list.php">শ্রেণি</a>
        <a href="/school_management/public/exam_results/add_exam_result.php">পরীক্ষা</a>
        <a href="/school_management/public/attendance/record_attendance.php">উপস্থিতি</a>
        <a href="/school_management/public/change_password.php">পাসওয়ার্ড পরিবর্তন</a>
        <a href="/school_management/public/logout.php">লগআউট</a>
    </div>
</div>
<div class="content">
    <div class="container">
        <h2>ফি সংগ্রহ</h2>
        <?php if ($message): ?>
            <p class="message-success"><?php echo $message; ?></p>
        <?php endif; ?>
        <?php if ($error): ?>
            <p class="message-error"><?php echo $error; ?></p>
        <?php endif; ?>
        
        <form action="" method="POST">
            <div class="form-group">
                <label for="class_id">শ্রেণি নির্বাচন করুন:</label>
                <select id="class_id" name="class_id" required>
                    <option value="">--শ্রেণি নির্বাচন করুন--</option>
                    <?php 
                    if ($classes_result && $classes_result->num_rows > 0) {
                        $classes_result->data_seek(0);
                        while ($row = $classes_result->fetch_assoc()): ?>
                            <option value="<?php echo htmlspecialchars($row['class_id']); ?>"><?php echo htmlspecialchars($row['class_name']); ?></option>
                        <?php endwhile; 
                    }
                    ?>
                </select>
            </div>
            <div class="form-group">
                <label for="student_id_dropdown">শিক্ষার্থী নির্বাচন করুন:</label>
                <select id="student_id_dropdown" name="student_id_dropdown" class="student-select">
                    <option value="">--শিক্ষার্থী নির্বাচন করুন--</option>
                </select>
            </div>
            <div class="form-group">
                <label for="student_id_input">অথবা সরাসরি আইডি দিন:</label>
                <input type="text" id="student_id_input" name="student_id" placeholder="শিক্ষার্থীর আইডি লিখুন">
            </div>
            <div class="form-group">
                <label for="memo_no">মেমো নং:</label>
                <input type="text" id="memo_no" name="memo_no" required> 
            </div>
            <div class="form-group">
                <label for="category_id">ফি-এর ধরন:</label>
                <select id="category_id" name="category_id" required>
                    <option value="">ফি-এর ধরন নির্বাচন করুন</option>
                    <?php
                    $categories_result->data_seek(0);
                    while ($row = $categories_result->fetch_assoc()) {
                        echo "<option value='{$row['category_id']}'>{$row['category_name']}</option>";
                    }
                    ?>
                </select>
            </div>
            <div id="monthly_fee_fields" style="display:none;">
                <div class="form-group">
                    <label for="fee_month">মাস:</label>
                    <input type="month" id="fee_month" name="fee_month">
                </div>
            </div>
            <div class="form-group">
                <label for="amount">জমা করা ফি:</label>
                <input type="number" step="0.01" id="amount" name="amount" required>
            </div>
            <div class="form-group">
                <label for="payment_method">পেমেন্টের মাধ্যম:</label>
                <select id="payment_method" name="payment_method" required>
                    <option value="Cash">ক্যাশ</option>
                    <option value="Bank">ব্যাংক</option>
                    <option value="Mobile Banking">মোবাইল ব্যাংকিং</option>
                </select>
            </div>
            <div class="form-group">
                <label for="payment_date">তারিখ:</label>
                <input type="date" id="payment_date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
            </div>
            <div class="form-buttons">
                <button type="submit">ফি সংগ্রহ করুন</button>
            </div>
        </form>
    </div>
</div>
<div class="footer">
    <p>&copy; <?php echo date("Y"); ?> স্কুল ম্যানেজমেন্ট সিস্টেম। সর্বস্বত্ব সংরক্ষিত।</p>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const classSelect = document.getElementById('class_id');
        const studentSelect = document.getElementById('student_id_dropdown');
        const studentInput = document.getElementById('student_id_input');
        const categorySelect = document.getElementById('category_id');
        const monthlyFeeFields = document.getElementById('monthly_fee_fields');
        const feeMonthInput = document.getElementById('fee_month');

        function fetchStudents(classId) {
            studentSelect.innerHTML = '<option value="">--শিক্ষার্থী লোড হচ্ছে--</option>';
            studentSelect.disabled = true;

            if (!classId) {
                studentSelect.innerHTML = '<option value="">--শিক্ষার্থী নির্বাচন করুন--</option>';
                studentSelect.disabled = false;
                return;
            }

            fetch(`/school_management/public/students/get_students_by_class.php?class_id=${classId}`)
                .then(response => response.json())
                .then(students => {
                    let options = '<option value="">--শিক্ষার্থী নির্বাচন করুন--</option>';
                    students.forEach(student => {
                        options += `<option value="${student.student_id}">${student.first_name} ${student.last_name} (${student.class_roll})</option>`;
                    });
                    studentSelect.innerHTML = options;
                    studentSelect.disabled = false;
                })
                .catch(error => console.error('Error fetching students:', error));
        }

        classSelect.addEventListener('change', function() {
            const selectedClassId = this.value;
            fetchStudents(selectedClassId);
            studentInput.value = '';
        });

        studentSelect.addEventListener('change', function() {
            const selectedStudentId = this.value;
            studentInput.value = selectedStudentId;
        });

        studentInput.addEventListener('input', function() {
            const typedStudentId = this.value;
            studentSelect.value = '';
        });

        categorySelect.addEventListener('change', function() {
            const selectedCategoryId = this.value;
            const monthlyFeeId = <?php echo json_encode($monthly_fee_id); ?>;
            const residentialFeeId = <?php echo json_encode($residential_fee_id); ?>;

            if (selectedCategoryId == monthlyFeeId || selectedCategoryId == residentialFeeId) {
                monthlyFeeFields.style.display = 'block';
                feeMonthInput.setAttribute('required', 'required');
            } else {
                monthlyFeeFields.style.display = 'none';
                feeMonthInput.removeAttribute('required');
            }
        });
    });
</script>
</body>
</html>