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

// Handle bKash callback
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Get the callback data
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        // Log the callback data for debugging
        error_log("bKash Callback Data: " . print_r($data, true));
        
        // Verify the payment
        if (isset($data['merchantInvoiceNumber'])) {
            $bKash = new bKashPayment();
            
            // Verify payment status
            $paymentInfo = $bKash->verifyPayment($data['merchantInvoiceNumber']);
            
            // Log verification result
            error_log("bKash Verification Result: " . print_r($paymentInfo, true));
            
            // Check if payment was successful
            if (isset($paymentInfo['transactionStatus']) && $paymentInfo['transactionStatus'] === 'Completed') {
                // Update payment request status
                $stmt = $pdo->prepare("
                    UPDATE bkash_payment_requests 
                    SET status = 'completed', transaction_id = ?, response_data = ?, updated_at = NOW()
                    WHERE merchant_invoice_number = ?
                ");
                $stmt->execute([
                    $paymentInfo['trxID'] ?? '',
                    json_encode($paymentInfo),
                    $data['merchantInvoiceNumber']
                ]);
                
                // Get student info from payment request
                $stmt = $pdo->prepare("
                    SELECT student_id, amount 
                    FROM bkash_payment_requests 
                    WHERE merchant_invoice_number = ?
                ");
                $stmt->execute([$data['merchantInvoiceNumber']]);
                $paymentRequest = $stmt->fetch();
                
                if ($paymentRequest) {
                    // Update student fees
                    updateStudentFees($pdo, $paymentRequest['student_id'], (float)$paymentRequest['amount']);
                    
                    // Insert fee payment record
                    insertFeePaymentRecord($pdo, $paymentRequest['student_id'], (float)$paymentRequest['amount'], $paymentInfo['trxID'] ?? '');
                }
                
                // Send success response to bKash
                header('Content-Type: application/json');
                echo json_encode(['status' => 'success']);
                exit();
            } else {
                // Update payment request status as failed
                $stmt = $pdo->prepare("
                    UPDATE bkash_payment_requests 
                    SET status = 'failed', response_data = ?, updated_at = NOW()
                    WHERE merchant_invoice_number = ?
                ");
                $stmt->execute([
                    json_encode($paymentInfo),
                    $data['merchantInvoiceNumber']
                ]);
                
                // Send failure response to bKash
                header('Content-Type: application/json');
                echo json_encode(['status' => 'failure']);
                exit();
            }
        }
    } catch (Exception $e) {
        error_log("bKash Callback Error: " . $e->getMessage());
        // Send failure response to bKash
        header('Content-Type: application/json');
        echo json_encode(['status' => 'failure']);
        exit();
    }
}

// If not a POST request, redirect to my fees page
header('Location: my_fees.php');
exit();

/**
 * Update student fees based on payment
 */
function updateStudentFees($pdo, $studentId, $amount) {
    try {
        // Get student ID from student_id field
        $stmt = $pdo->prepare("SELECT id FROM students WHERE student_id = ? LIMIT 1");
        $stmt->execute([$studentId]);
        $student = $stmt->fetch();
        
        if (!$student) {
            throw new Exception("Student not found: " . $studentId);
        }
        
        $actualStudentId = $student['id'];
        
        // Get due fees for this student
        $stmt = $pdo->prepare("
            SELECT id, amount, paid_amount 
            FROM fees 
            WHERE student_id = ? AND status IN ('pending', 'partial', 'overdue') 
            ORDER BY due_date ASC
        ");
        $stmt->execute([$actualStudentId]);
        $due_fees = $stmt->fetchAll();
        
        $remaining_amount = $amount;
        
        foreach ($due_fees as $fee) {
            if ($remaining_amount <= 0) break;
            
            $due_amount = $fee['amount'] - $fee['paid_amount'];
            $payment_amount = min($remaining_amount, $due_amount);
            
            $new_paid_amount = $fee['paid_amount'] + $payment_amount;
            $new_status = ($new_paid_amount >= $fee['amount']) ? 'paid' : 'partial';
            
            $stmt = $pdo->prepare("
                UPDATE fees 
                SET paid_amount = ?, status = ?, paid_date = IF(paid_date IS NULL, CURDATE(), paid_date)
                WHERE id = ?
            ");
            $stmt->execute([$new_paid_amount, $new_status, $fee['id']]);
            
            $remaining_amount -= $payment_amount;
        }
        
    } catch (Exception $e) {
        error_log("Error updating student fees: " . $e->getMessage());
        throw $e;
    }
}

/**
 * Insert fee payment record
 */
function insertFeePaymentRecord($pdo, $studentId, $amount, $transactionId) {
    try {
        // Get student ID from student_id field
        $stmt = $pdo->prepare("SELECT id FROM students WHERE student_id = ? LIMIT 1");
        $stmt->execute([$studentId]);
        $student = $stmt->fetch();
        
        if (!$student) {
            throw new Exception("Student not found: " . $studentId);
        }
        
        $actualStudentId = $student['id'];
        
        // Get due fees for this student to distribute payment
        $stmt = $pdo->prepare("
            SELECT id, amount, paid_amount 
            FROM fees 
            WHERE student_id = ? AND status IN ('pending', 'partial', 'overdue') 
            ORDER BY due_date ASC
        ");
        $stmt->execute([$actualStudentId]);
        $due_fees = $stmt->fetchAll();
        
        $remaining_amount = $amount;
        
        foreach ($due_fees as $fee) {
            if ($remaining_amount <= 0) break;
            
            $due_amount = $fee['amount'] - $fee['paid_amount'];
            $payment_amount = min($remaining_amount, $due_amount);
            
            // Insert payment record for this specific fee
            $ins = $pdo->prepare("
                INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, transaction_id, notes, created_by) 
                VALUES (?, ?, NOW(), ?, ?, ?, ?)
            ");
            $ins->execute([
                $fee['id'], 
                $payment_amount, 
                'bkash', 
                $transactionId, 
                'bKash payment verified automatically', 
                $_SESSION['user_id'] ?? null
            ]);
            
            $remaining_amount -= $payment_amount;
        }
        
    } catch (Exception $e) {
        error_log("Error inserting fee payment record: " . $e->getMessage());
        throw $e;
    }
}
?>