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

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

// Get student from user
$stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section FROM students s LEFT JOIN classes c ON s.class_id=c.id WHERE s.user_id=? LIMIT 1");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch();
if (!$student) { die('Student profile not found'); }

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_transaction'])) {
    try {
        $transaction_id = trim($_POST['transaction_id']);
        $bank_account_id = (int)$_POST['bank_account_id'];
        $amount = (float)$_POST['amount'];
        // Get selected fee IDs if provided
        $selected_fee_ids = isset($_POST['selected_fee_ids']) ? json_decode($_POST['selected_fee_ids'], true) : [];
        
        // Validate inputs
        if (empty($transaction_id) || $bank_account_id <= 0 || $amount <= 0) {
            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 by any student
        $stmt = $pdo->prepare("SELECT bt.id, s.first_name, s.last_name, s.student_id as student_code FROM bank_transactions bt JOIN students s ON bt.student_id = s.id WHERE bt.transaction_id = ?");
        $stmt->execute([$transaction_id]);
        $existing_transaction = $stmt->fetch();
        if ($existing_transaction) {
            throw new Exception("এই ট্রানজেকশন আইডি ইতিমধ্যে ছাত্র/ছাত্রী " . 
                $existing_transaction['student_code'] . " (" . 
                $existing_transaction['first_name'] . " " . 
                $existing_transaction['last_name'] . ") দ্বারা ব্যবহার করা হয়েছে। অনন্য ট্রানজেকশন আইডি ব্যবহার করুন।");
        }
        
        // Handle receipt image upload
        $receipt_image_path = null;
        
        // First check if there's a captured image from the camera
        if (isset($_POST['captured_image_data']) && !empty($_POST['captured_image_data'])) {
            // Process base64 encoded image data
            $imageData = $_POST['captured_image_data'];
            
            // Remove data:image/jpeg;base64, part if present
            if (strpos($imageData, 'data:image') === 0) {
                $parts = explode(',', $imageData);
                if (count($parts) == 2) {
                    $imageData = $parts[1];
                }
            }
            
            // Decode base64 image data
            $decodedData = base64_decode($imageData);
            if ($decodedData === false) {
                throw new Exception("ছবি ডিকোড করতে সমস্যা হচ্ছে");
            }
            
            // Determine file extension from the original data URL
            $extension = 'jpg'; // default
            if (strpos($_POST['captured_image_data'], 'data:image/png') !== false) {
                $extension = 'png';
            } elseif (strpos($_POST['captured_image_data'], 'data:image/jpeg') !== false) {
                $extension = 'jpg';
            } elseif (strpos($_POST['captured_image_data'], 'data:image/gif') !== false) {
                $extension = 'gif';
            }
            
            $upload_dir = '../uploads/bank_receipts/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $filename = 'receipt_' . $student['id'] . '_' . time() . '_' . uniqid() . '.' . $extension;
            $target_path = $upload_dir . $filename;
            
            if (file_put_contents($target_path, $decodedData) === false) {
                throw new Exception("রসিদ আপলোড করা যায়নি");
            }
            
            $receipt_image_path = 'uploads/bank_receipts/' . $filename;
        } 
        // If no captured image, check for uploaded file
        elseif (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 pending status
        $stmt = $pdo->prepare("
            INSERT INTO bank_transactions (student_id, bank_account_id, amount, transaction_id, receipt_image, status, submitted_at) 
            VALUES (?, ?, ?, ?, ?, 'pending', NOW())
        ");
        $stmt->execute([$student['id'], $bank_account_id, $amount, $transaction_id, $receipt_image_path]);
        
        // Get the inserted transaction ID
        $transaction_id_db = $pdo->lastInsertId();
        
        // Store selected fee IDs if any were selected
        if (!empty($selected_fee_ids)) {
            foreach ($selected_fee_ids as $fee_id) {
                $stmt = $pdo->prepare("INSERT INTO bank_transaction_selected_fees (transaction_id, fee_id) VALUES (?, ?)");
                $stmt->execute([$transaction_id_db, $fee_id]);
            }
        }
        
        $_SESSION['success_message'] = 'ট্রানজেকশন আইডি সফলভাবে জমা হয়েছে। অ্যাডমিন শীঘ্রই এটি ভেরিফাই করবেন।';
        header('Location: submit_bank_transaction.php');
        exit();
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// 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 = [];
}

// Get search parameters
$search_pending = isset($_GET['search_pending']) ? trim($_GET['search_pending']) : '';
$search_verified = isset($_GET['search_verified']) ? trim($_GET['search_verified']) : '';
$search_rejected = isset($_GET['search_rejected']) ? trim($_GET['search_rejected']) : '';

// Get all bank transactions for this student (pending, verified, and rejected) with search filters
$stmt = $pdo->prepare("
    SELECT bt.*, ba.bank_name, ba.branch_name, ba.account_number, u.username as verified_by_name
    FROM bank_transactions bt
    LEFT JOIN bank_accounts ba ON bt.bank_account_id = ba.id
    LEFT JOIN users u ON bt.verified_by = u.id
    WHERE bt.student_id = ?
    ORDER BY bt.submitted_at DESC
");
$stmt->execute([$student['id']]);
$all_transactions = $stmt->fetchAll();

// Group transactions by status and apply search filters
$pending_transactions = [];
$verified_transactions = [];
$rejected_transactions = [];

foreach ($all_transactions as $transaction) {
    switch ($transaction['status']) {
        case 'pending':
            // Apply search filter for pending transactions
            if (empty($search_pending) || 
                stripos($transaction['transaction_id'], $search_pending) !== false || 
                stripos((string)$transaction['amount'], $search_pending) !== false) {
                $pending_transactions[] = $transaction;
            }
            break;
        case 'verified':
            // Apply search filter for verified transactions
            if (empty($search_verified) || 
                stripos($transaction['transaction_id'], $search_verified) !== false || 
                stripos((string)$transaction['amount'], $search_verified) !== false) {
                $verified_transactions[] = $transaction;
            }
            break;
        case 'rejected':
            // Apply search filter for rejected transactions
            if (empty($search_rejected) || 
                stripos($transaction['transaction_id'], $search_rejected) !== false || 
                stripos((string)$transaction['amount'], $search_rejected) !== false) {
                $rejected_transactions[] = $transaction;
            }
            break;
    }
}

// Check for messages from session
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['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="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;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-verified {
            background-color: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .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);
        }
        #camera-container {
            position: relative;
        }
        #video-preview {
            background-color: #000;
            border-radius: 4px;
        }
        .camera-btn-group {
            margin-top: 10px;
        }
    </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="../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-4 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 class="col-md-4 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-4 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>
                        
                        <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>
                        
                        <!-- Camera capture section -->
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-camera"></i> ক্যামেরা থেকে রসিদ তুলুন</label>
                            <div id="camera-container" class="border rounded p-3 bg-light">
                                <video id="video-preview" width="100%" height="240" autoplay playsinline style="display:none;"></video>
                                <canvas id="canvas" style="display:none;"></canvas>
                                <div id="camera-controls" class="d-flex flex-column align-items-center">
                                    <button type="button" id="start-camera" class="btn btn-outline-primary mb-2"><i class="fas fa-video"></i> ক্যামেরা চালু করুন</button>
                                    <button type="button" id="capture-photo" class="btn btn-success mb-2" disabled><i class="fas fa-camera"></i> ছবি তুলুন</button>
                                    <button type="button" id="stop-camera" class="btn btn-outline-secondary" disabled><i class="fas fa-stop"></i> ক্যামেরা বন্ধ করুন</button>
                                </div>
                                <div id="captured-image-container" class="mt-3" style="display:none;">
                                    <img id="captured-image" src="" alt="Captured Receipt" class="img-thumbnail" style="max-width: 100%; height: auto;">
                                    <div class="mt-2">
                                        <button type="button" id="retake-photo" class="btn btn-warning btn-sm"><i class="fas fa-redo"></i> আবার তুলুন</button>
                                        <button type="button" id="use-photo" class="btn btn-success btn-sm"><i class="fas fa-check"></i> ছবি ব্যবহার করুন</button>
                                    </div>
                                </div>
                                <input type="hidden" id="captured-image-data" name="captured_image_data">
                            </div>
                        </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>
            
            <!-- Pending Transactions -->
            <?php if (!empty($pending_transactions)): ?>
                <div class="card mb-4">
                    <div class="card-header">
                        <h5><i class="fas fa-clock"></i> মুলতুবি ট্রানজেকশন</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead class="table-dark">
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>ট্রানজেকশন আইডি</th>
                                        <th>ব্যাংক</th>
                                        <th>পরিমাণ</th>
                                        <th>অবস্থা</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pending_transactions as $transaction): ?>
                                        <tr>
                                            <td><?= date('d/m/Y', strtotime($transaction['submitted_at'])) ?></td>
                                            <td><?= htmlspecialchars($transaction['transaction_id']) ?></td>
                                            <td><?= htmlspecialchars($transaction['bank_name']) ?> - <?= htmlspecialchars($transaction['branch_name']) ?></td>
                                            <td>৳<?= number_format((float)$transaction['amount'], 2) ?></td>
                                            <td><span class="badge status-pending">মুলতুবি</span></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Verified Transactions -->
            <?php if (!empty($verified_transactions)): ?>
                <div class="card mb-4">
                    <div class="card-header">
                        <h5><i class="fas fa-check-circle"></i> ভেরিফাইড ট্রানজেকশন</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead class="table-dark">
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>ট্রানজেকশন আইডি</th>
                                        <th>ব্যাংক</th>
                                        <th>পরিমাণ</th>
                                        <th>অবস্থা</th>
                                        <th>ভেরিফাই করেছেন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($verified_transactions as $transaction): ?>
                                        <tr>
                                            <td><?= date('d/m/Y', strtotime($transaction['submitted_at'])) ?></td>
                                            <td><?= htmlspecialchars($transaction['transaction_id']) ?></td>
                                            <td><?= htmlspecialchars($transaction['bank_name']) ?> - <?= htmlspecialchars($transaction['branch_name']) ?></td>
                                            <td>৳<?= number_format((float)$transaction['amount'], 2) ?></td>
                                            <td><span class="badge status-verified">ভেরিফাইড</span></td>
                                            <td><?= htmlspecialchars($transaction['verified_by_name'] ?? 'N/A') ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Rejected Transactions -->
            <?php if (!empty($rejected_transactions)): ?>
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-times-circle"></i> প্রত্যাখ্যাত ট্রানজেকশন</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead class="table-dark">
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>ট্রানজেকশন আইডি</th>
                                        <th>ব্যাংক</th>
                                        <th>পরিমাণ</th>
                                        <th>অবস্থা</th>
                                        <th>ভেরিফাই করেছেন</th>
                                        <th>নোট</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($rejected_transactions as $transaction): ?>
                                        <tr>
                                            <td><?= date('d/m/Y', strtotime($transaction['submitted_at'])) ?></td>
                                            <td><?= htmlspecialchars($transaction['transaction_id']) ?></td>
                                            <td><?= htmlspecialchars($transaction['bank_name']) ?> - <?= htmlspecialchars($transaction['branch_name']) ?></td>
                                            <td>৳<?= number_format((float)$transaction['amount'], 2) ?></td>
                                            <td><span class="badge status-rejected">প্রত্যাখ্যাত</span></td>
                                            <td><?= htmlspecialchars($transaction['verified_by_name'] ?? 'N/A') ?></td>
                                            <td><?= htmlspecialchars($transaction['notes'] ?? 'N/A') ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <?php if (empty($pending_transactions) && empty($verified_transactions) && empty($rejected_transactions)): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> কোন ট্রানজেকশন রেকর্ড পাওয়া যায়নি।
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Camera functionality for capturing receipt images
let videoStream = null;

// Start camera
const startCameraBtn = document.getElementById('start-camera');
const stopCameraBtn = document.getElementById('stop-camera');
const capturePhotoBtn = document.getElementById('capture-photo');
const videoPreview = document.getElementById('video-preview');
const canvas = document.getElementById('canvas');
const capturedImage = document.getElementById('captured-image');
const capturedImageContainer = document.getElementById('captured-image-container');
const retakePhotoBtn = document.getElementById('retake-photo');
const usePhotoBtn = document.getElementById('use-photo');
const cameraControls = document.getElementById('camera-controls');
const capturedImageDataInput = document.getElementById('captured-image-data');

startCameraBtn.addEventListener('click', async () => {
    try {
        videoStream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: 'environment' } // Prefer rear camera if available
        });
        
        videoPreview.srcObject = videoStream;
        videoPreview.style.display = 'block';
        
        startCameraBtn.disabled = true;
        stopCameraBtn.disabled = false;
        capturePhotoBtn.disabled = false;
    } catch (err) {
        console.error('Error accessing camera:', err);
        alert('ক্যামেরা ব্যবহার করতে সমস্যা হচ্ছে: ' + err.message);
    }
});

// Stop camera
stopCameraBtn.addEventListener('click', () => {
    if (videoStream) {
        videoStream.getTracks().forEach(track => track.stop());
        videoStream = null;
    }
    
    videoPreview.style.display = 'none';
    videoPreview.srcObject = null;
    
    startCameraBtn.disabled = false;
    stopCameraBtn.disabled = true;
    capturePhotoBtn.disabled = true;
});

// Capture photo
capturePhotoBtn.addEventListener('click', () => {
    const context = canvas.getContext('2d');
    canvas.width = videoPreview.videoWidth;
    canvas.height = videoPreview.videoHeight;
    
    context.drawImage(videoPreview, 0, 0, canvas.width, canvas.height);
    
    const imageDataUrl = canvas.toDataURL('image/jpeg', 0.8); // JPEG with 80% quality
    
    capturedImage.src = imageDataUrl;
    capturedImageContainer.style.display = 'block';
    
    // Hide camera controls temporarily
    cameraControls.style.display = 'none';
});

// Retake photo
retakePhotoBtn.addEventListener('click', () => {
    capturedImageContainer.style.display = 'none';
    cameraControls.style.display = 'flex';
});

// Use captured photo
usePhotoBtn.addEventListener('click', () => {
    const imageDataUrl = capturedImage.src;
    capturedImageDataInput.value = imageDataUrl;
    
    // Show a confirmation
    alert('ছবি সফলভাবে গ্রহণ করা হয়েছে! ফর্ম সাবমিট করুন।');
    
    // Stop camera if it's still running
    if (videoStream) {
        videoStream.getTracks().forEach(track => track.stop());
        videoStream = null;
        videoPreview.style.display = 'none';
        videoPreview.srcObject = null;
        startCameraBtn.disabled = false;
        stopCameraBtn.disabled = true;
        capturePhotoBtn.disabled = true;
    }
});

// Handle form submission to prioritize captured image over file upload
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
    // If we have a captured image, clear the file input to avoid conflicts
    if (capturedImageDataInput.value) {
        document.getElementById('receipt_image').value = '';
    }
});

// Update UI when a file is selected manually
document.getElementById('receipt_image').addEventListener('change', function() {
    if (this.files.length > 0) {
        // Clear the captured image if a file is uploaded
        capturedImageDataInput.value = '';
        
        // Reset camera UI
        capturedImageContainer.style.display = 'none';
        cameraControls.style.display = 'flex';
        
        // Stop camera if it's running
        if (videoStream) {
            videoStream.getTracks().forEach(track => track.stop());
            videoStream = null;
            videoPreview.style.display = 'none';
            videoPreview.srcObject = null;
            startCameraBtn.disabled = false;
            stopCameraBtn.disabled = true;
            capturePhotoBtn.disabled = true;
        }
    }
});
</script>
</body>
</html>