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

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

$error_message = '';
$success_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_transaction'])) {
    try {
        $student_id = (int)$_POST['student_id'];
        $bank_account_id = (int)$_POST['bank_account_id'];
        $amount = (float)$_POST['amount'];
        $transaction_id = trim($_POST['transaction_id']);
        
        // Validate inputs
        if ($student_id <= 0 || $bank_account_id <= 0 || $amount <= 0 || empty($transaction_id)) {
            throw new Exception("সকল তথ্য প্রয়োজন");
        }
        
        // Check if student exists
        $stmt = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE id = ?");
        $stmt->execute([$student_id]);
        $student = $stmt->fetch();
        if (!$student) {
            throw new Exception("ছাত্র/ছাত্রী খুঁজে পাওয়া যায়নি");
        }
        
        // Check if bank account exists and is active
        $stmt = $pdo->prepare("SELECT id FROM bank_accounts WHERE id = ? AND status = 'active'");
        $stmt->execute([$bank_account_id]);
        if (!$stmt->fetch()) {
            throw new Exception("ব্যাংক অ্যাকাউন্ট খুঁজে পাওয়া যায়নি বা নিষ্ক্রিয় অবস্থায় আছে");
        }
        
        // Check if the transaction ID is already used
        $stmt = $pdo->prepare("SELECT id FROM bank_transactions WHERE transaction_id = ? AND student_id = ?");
        $stmt->execute([$transaction_id, $student_id]);
        if ($stmt->fetch()) {
            throw new Exception("এই ট্রানজেকশন আইডি ইতিমধ্যে ব্যবহার করা হয়েছে। অনন্য ট্রানজেকশন আইডি ব্যবহার করুন।");
        }
        
        // Handle receipt image upload
        $receipt_image_path = null;
        if (isset($_FILES['receipt_image']) && $_FILES['receipt_image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../uploads/bank_receipts/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = strtolower(pathinfo($_FILES['receipt_image']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (!in_array($file_extension, $allowed_extensions)) {
                throw new Exception("অ্যালাউড ফাইল ফরম্যাট: JPG, PNG, GIF");
            }
            
            if ($_FILES['receipt_image']['size'] > 2097152) { // 2MB
                throw new Exception("ফাইলের সাইজ ২MB এর কম হতে হবে");
            }
            
            $filename = 'receipt_' . $student_id . '_' . time() . '_' . uniqid() . '.' . $file_extension;
            $target_path = $upload_dir . $filename;
            
            if (!move_uploaded_file($_FILES['receipt_image']['tmp_name'], $target_path)) {
                throw new Exception("রসিদ আপলোড করা যায়নি");
            }
            
            $receipt_image_path = 'uploads/bank_receipts/' . $filename;
        }
        
        // Insert transaction with verified status (since admin is submitting)
        $stmt = $pdo->prepare("
            INSERT INTO bank_transactions (student_id, bank_account_id, amount, transaction_id, receipt_image, status, submitted_at, verified_at, verified_by) 
            VALUES (?, ?, ?, ?, ?, 'verified', NOW(), NOW(), ?)
        ");
        $stmt->execute([$student_id, $bank_account_id, $amount, $transaction_id, $receipt_image_path, $_SESSION['user_id']]);
        
        $success_message = 'ট্রানজেকশন সফলভাবে জমা হয়েছে।';
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Get students for dropdown
$students = [];
try {
    $stmt = $pdo->query("SELECT id, student_id, first_name, last_name FROM students ORDER BY first_name, last_name");
    $students = $stmt->fetchAll();
} catch (Exception $e) {
    $students = [];
}

// Get bank accounts for dropdown
$bank_accounts = [];
try {
    $stmt = $pdo->query("SELECT id, bank_name, branch_name, account_number, account_name FROM bank_accounts WHERE status = 'active' ORDER BY bank_name, branch_name");
    $bank_accounts = $stmt->fetchAll();
} catch (Exception $e) {
    $bank_accounts = [];
}
?>

<!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>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
            border-radius: 0.5rem;
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid rgba(0, 0, 0, 0.125);
            font-weight: 600;
        }
        .table th {
            font-weight: 600;
        }
        .form-control, .form-select {
            border-radius: 0.375rem;
        }
        .btn {
            border-radius: 0.375rem;
        }
        .navbar {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
    </style>
</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-home"></i> ড্যাশবোর্ড</a>
            <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>
</nav>

<div class="container-fluid mt-4">
    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <div class="row">
        <div class="col-md-12">
            <h3><i class="fas fa-file-invoice-dollar"></i> ব্যাংক ডিপোজিট জমা</h3>
            
            <!-- Submit Transaction Form -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-plus-circle"></i> নতুন ব্যাংক ডিপোজিট জমা দিন</h5>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label for="student_id" class="form-label"><i class="fas fa-user-graduate"></i> ছাত্র/ছাত্রী <span class="text-danger">*</span></label>
                                <select class="form-select" id="student_id" name="student_id" required>
                                    <option value="">ছাত্র/ছাত্রী নির্বাচন করুন</option>
                                    <?php foreach ($students as $student): ?>
                                        <option value="<?= $student['id'] ?>">
                                            <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?> (<?= htmlspecialchars($student['student_id']) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-3 mb-3">
                                <label for="bank_account_id" class="form-label"><i class="fas fa-university"></i> ব্যাংক অ্যাকাউন্ট <span class="text-danger">*</span></label>
                                <select class="form-select" id="bank_account_id" name="bank_account_id" required>
                                    <option value="">ব্যাংক নির্বাচন করুন</option>
                                    <?php foreach ($bank_accounts as $account): ?>
                                        <option value="<?= $account['id'] ?>">
                                            <?= htmlspecialchars($account['bank_name']) ?> - <?= htmlspecialchars($account['branch_name']) ?> (<?= htmlspecialchars($account['account_number']) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-3 mb-3">
                                <label for="amount" class="form-label"><i class="fas fa-money-bill-wave"></i> পরিমাণ (৳) <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="amount" name="amount" step="0.01" min="0" placeholder="পরিমাণ" required>
                            </div>
                            
                            <div class="col-md-3 mb-3">
                                <label for="transaction_id" class="form-label"><i class="fas fa-hashtag"></i> ট্রানজেকশন আইডি <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="transaction_id" name="transaction_id" placeholder="ব্যাংক ট্রানজেকশন আইডি" required>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="receipt_image" class="form-label"><i class="fas fa-image"></i> রসিদের ছবি (JPG, PNG, GIF - Max 2MB)</label>
                            <input type="file" class="form-control" id="receipt_image" name="receipt_image" accept=".jpg,.jpeg,.png,.gif">
                        </div>
                        
                        <button type="submit" name="submit_transaction" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i> জমা দিন
                        </button>
                    </form>
                    
                    <div class="mt-3">
                        <h6><i class="fas fa-info-circle"></i> নির্দেশনা:</h6>
                        <ul>
                            <li>ছাত্র/ছাত্রী নির্বাচন করুন</li>
                            <li>ব্যাংক অ্যাকাউন্ট নির্বাচন করুন</li>
                            <li>ব্যাংক ট্রানজেকশন আইডি প্রবেস করান</li>
                            <li>পেমেন্ট পরিমাণ নিশ্চিত করুন</li>
                            <li>রসিদের ছবি আপলোড করুন (ঐচ্ছিক)</li>
                            <li>"জমা দিন" বাটনে ক্লিক করুন</li>
                        </ul>
                    </div>
                </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>