<?php
/**
 * Merchant Payment Processing for Fee Collection
 * 
 * This file handles merchant account payment processing for the fee payment dashboard
 */

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

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

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json; charset=UTF-8');
    
    try {
        $action = $_POST['action'];
        
        if ($action === 'initiate_merchant_payment') {
            $student_id = intval($_POST['student_id'] ?? 0);
            $amount = floatval($_POST['amount'] ?? 0);
            $payment_method = trim($_POST['payment_method'] ?? 'bkash');
            $phone_number = trim($_POST['phone_number'] ?? '');
            
            if ($student_id <= 0 || $amount <= 0 || empty($phone_number)) {
                echo json_encode(['success' => false, 'message' => 'Invalid payment data']);
                exit();
            }
            
            // Get student details
            $stmt = $pdo->prepare("
                SELECT s.*, c.name as class_name, c.section 
                FROM students s 
                JOIN classes c ON s.class_id = c.id 
                WHERE s.id = ?
            ");
            $stmt->execute([$student_id]);
            $student = $stmt->fetch();
            
            if (!$student) {
                echo json_encode(['success' => false, 'message' => 'Student not found']);
                exit();
            }
            
            // Generate merchant invoice number
            $merchant_invoice = 'FEE_' . date('Ymd') . '_' . uniqid();
            
            // Store payment request in database
            $stmt = $pdo->prepare("
                INSERT INTO merchant_payment_requests 
                (merchant_invoice, student_id, amount, payment_method, phone_number, status, created_at) 
                VALUES (?, ?, ?, ?, ?, 'pending', NOW())
            ");
            $stmt->execute([$merchant_invoice, $student_id, $amount, $payment_method, $phone_number]);
            $payment_request_id = $pdo->lastInsertId();
            
            // Prepare response based on payment method
            $response = [
                'success' => true,
                'merchant_invoice' => $merchant_invoice,
                'payment_request_id' => $payment_request_id,
                'student_name' => $student['first_name'] . ' ' . $student['last_name'],
                'student_id' => $student['student_id'],
                'class' => $student['class_name'] . ' - ' . $student['section'],
                'amount' => $amount
            ];
            
            // Handle different payment methods
            switch ($payment_method) {
                case 'bkash':
                    // Check if bKash is enabled
                    $bKash = new bKashPayment();
                    if ($bKash->isEnabled()) {
                        // Create bKash payment
                        $student_info = [
                            'student_id' => $student['student_id'],
                            'name' => $student['first_name'] . ' ' . $student['last_name'],
                            'phone' => $phone_number
                        ];
                        
                        $payment = $bKash->createPayment($amount, $student_info);
                        $response['payment_url'] = $payment['paymentUrl'];
                        $response['type'] = 'redirect';
                    } else {
                        // Manual bKash payment instructions
                        $response['type'] = 'manual';
                        $response['instructions'] = 'bKash এ পেমেন্ট করতে নিচের ধাপগুলো অনুসরণ করুন:<br>
                        1. bKash অ্যাপ খুলুন বা *247# ডায়াল করুন<br>
                        2. "Send Money" অপশন সিলেক্ট করুন<br>
                        3. রিসিভার নাম্বার: ' . get_merchant_number('bkash') . '<br>
                        4. পরিমাণ: ' . number_format($amount, 2) . ' টাকা<br>
                        5. রেফারেন্স: ' . $merchant_invoice . '<br>
                        6. PIN দিয়ে পেমেন্ট সম্পন্ন করুন<br>
                        7. ট্রানজেকশন আইডি নোট করুন';
                    }
                    break;
                    
                case 'nagad':
                    // Manual Nagad payment instructions
                    $response['type'] = 'manual';
                    $response['instructions'] = 'Nagad এ পেমেন্ট করতে নিচের ধাপগুলো অনুসরণ করুন:<br>
                    1. Nagad অ্যাপ খুলুন<br>
                    2. "Send Money" অপশন সিলেক্ট করুন<br>
                    3. রিসিভার নাম্বার: ' . get_merchant_number('nagad') . '<br>
                    4. পরিমাণ: ' . number_format($amount, 2) . ' টাকা<br>
                    5. রেফারেন্স: ' . $merchant_invoice . '<br>
                    6. PIN দিয়ে পেমেন্ট সম্পন্ন করুন<br>
                    7. ট্রানজেকশন আইডি নোট করুন';
                    break;
                    
                case 'rocket':
                    // Manual Rocket payment instructions
                    $response['type'] = 'manual';
                    $response['instructions'] = 'Rocket এ পেমেন্ট করতে নিচের ধাপগুলো অনুসরণ করুন:<br>
                    1. *322# ডায়াল করুন<br>
                    2. "Send Money" অপশন সিলেক্ট করুন<br>
                    3. রিসিভার নাম্বার: ' . get_merchant_number('rocket') . '<br>
                    4. পরিমাণ: ' . number_format($amount, 2) . ' টাকা<br>
                    5. রেফারেন্স: ' . $merchant_invoice . '<br>
                    6. PIN দিয়ে পেমেন্ট সম্পন্ন করুন<br>
                    7. ট্রানজেকশন আইডি নোট করুন';
                    break;
                    
                default:
                    $response['type'] = 'manual';
                    $response['instructions'] = 'পেমেন্ট করতে নিচের ধাপগুলো অনুসরণ করুন:<br>
                    1. ' . ucfirst($payment_method) . ' এ পেমেন্ট করুন<br>
                    2. মার্চেন্ট নাম্বার: ' . get_merchant_number($payment_method) . '<br>
                    3. পরিমাণ: ' . number_format($amount, 2) . ' টাকা<br>
                    4. রেফারেন্স: ' . $merchant_invoice . '<br>
                    5. ট্রানজেকশন আইডি নোট করুন';
            }
            
            echo json_encode($response);
            exit();
        }
        
        if ($action === 'verify_payment') {
            $payment_request_id = intval($_POST['payment_request_id'] ?? 0);
            $transaction_id = trim($_POST['transaction_id'] ?? '');
            
            if ($payment_request_id <= 0 || empty($transaction_id)) {
                echo json_encode(['success' => false, 'message' => 'Invalid verification data']);
                exit();
            }
            
            // Update payment request with transaction ID
            $stmt = $pdo->prepare("
                UPDATE merchant_payment_requests 
                SET transaction_id = ?, status = 'completed', verified_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$transaction_id, $payment_request_id]);
            
            // Get payment request details
            $stmt = $pdo->prepare("
                SELECT * FROM merchant_payment_requests WHERE id = ?
            ");
            $stmt->execute([$payment_request_id]);
            $payment_request = $stmt->fetch();
            
            if (!$payment_request) {
                echo json_encode(['success' => false, 'message' => 'Payment request not found']);
                exit();
            }
            
            // Process the fee payment
            $stmt = $pdo->prepare("
                INSERT INTO fee_payments 
                (fee_id, amount, payment_date, payment_method, transaction_id, notes, created_by) 
                VALUES (?, ?, NOW(), ?, ?, 'Merchant payment verified', ?)
            ");
            $stmt->execute([0, $payment_request['amount'], $payment_request['payment_method'], $transaction_id, $_SESSION['user_id']]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Payment verified successfully',
                'payment_request' => $payment_request
            ]);
            exit();
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        exit();
    }
}

/**
 * Get merchant number for payment method
 */
function get_merchant_number($method) {
    // In a real implementation, this would come from database settings
    $merchant_numbers = [
        'bkash' => '017XXXXXXXX',
        'nagad' => '018XXXXXXXX',
        'rocket' => '019XXXXXXXX'
    ];
    
    return $merchant_numbers[$method] ?? '01XXXXXXXXX';
}

/**
 * Create merchant payment tables
 */
function create_merchant_payment_tables() {
    global $pdo;
    
    try {
        // Create merchant payment requests table
        $sql = "
        CREATE TABLE IF NOT EXISTS merchant_payment_requests (
            id INT AUTO_INCREMENT PRIMARY KEY,
            merchant_invoice VARCHAR(100) NOT NULL UNIQUE,
            student_id INT NOT NULL,
            amount DECIMAL(10,2) NOT NULL,
            payment_method VARCHAR(50) NOT NULL,
            phone_number VARCHAR(20),
            transaction_id VARCHAR(100),
            status ENUM('pending', 'completed', 'failed', 'cancelled') DEFAULT 'pending',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            verified_at TIMESTAMP NULL,
            
            INDEX idx_merchant_invoice (merchant_invoice),
            INDEX idx_student_id (student_id),
            INDEX idx_status (status),
            INDEX idx_created_at (created_at)
        )";
        
        $pdo->exec($sql);
        
        return true;
    } catch (Exception $e) {
        error_log("Error creating merchant payment tables: " . $e->getMessage());
        return false;
    }
}
?>