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

// Authentication check
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$student_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle JSON input for API calls
    $input = json_decode(file_get_contents('php://input'), true);
    
    if ($input) {
        // Process API request
        $amount = floatval($input['amount']);
        $wallet_id = intval($input['wallet_id']);
        $reference = $conn->real_escape_string($input['reference']);
        $payment_method = $conn->real_escape_string($input['payment_method']);
        $status = isset($input['status']) ? $conn->real_escape_string($input['status']) : 'pending';
        
        // Validate inputs
        if ($amount <= 0) {
            echo json_encode(['success' => false, 'message' => 'Amount must be greater than zero']);
            exit();
        }
        
        // Check wallet belongs to student
        $wallet_check = $conn->prepare("SELECT id FROM student_wallets WHERE id = ? AND student_id = ?");
        $wallet_check->bind_param("ii", $wallet_id, $student_id);
        $wallet_check->execute();
        $wallet_check->store_result();
        
        if ($wallet_check->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Invalid wallet']);
            exit();
        }
        
        $conn->begin_transaction();
        
        try {
            // Create transaction record
            $transaction_stmt = $conn->prepare("
                INSERT INTO wallet_transactions (
                    wallet_id, amount, transaction_type, reference, payment_method, status, description
                ) VALUES (?, ?, 'deposit', ?, ?, ?, ?)
            ");
            $description = "Deposit via " . ucfirst($payment_method);
            $transaction_stmt->bind_param(
                "idssss", 
                $wallet_id, 
                $amount, 
                $reference, 
                $payment_method,
                $status,
                $description
            );
            $transaction_stmt->execute();
            
            // If payment is already completed, update wallet balance
            if ($status === 'completed') {
                $update_stmt = $conn->prepare("
                    UPDATE student_wallets 
                    SET balance = balance + ? 
                    WHERE id = ?
                ");
                $update_stmt->bind_param("di", $amount, $wallet_id);
                $update_stmt->execute();
                
                // Send notification to student
                $notification_stmt = $conn->prepare("
                    INSERT INTO notifications (
                        user_id, user_type, title, message, is_read
                    ) VALUES (?, 'student', 'Wallet Credited', ?, 0)
                ");
                $message = "Your wallet has been credited with " . $amount . ". Reference: " . $reference;
                $notification_stmt->bind_param("is", $student_id, $message);
                $notification_stmt->execute();
            }
            
            $conn->commit();
            
            echo json_encode(['success' => true, 'message' => 'Transaction recorded']);
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(['success' => false, 'message' => 'Error processing deposit: ' . $e->getMessage()]);
        }
        
        exit();
    }
    
    // Handle form submission for bank transfers
    if (isset($_POST['deposit_funds'])) {
        $amount = floatval($_POST['amount']);
        $wallet_id = intval($_POST['wallet_id']);
        $bank_account_id = intval($_POST['bank_account_id']);
        
        // Validate inputs
        if ($amount <= 0) {
            $_SESSION['error'] = "Amount must be greater than zero";
            header("Location: wallet.php");
            exit();
        }
        
        // Check wallet belongs to student
        $wallet_check = $conn->prepare("SELECT id FROM student_wallets WHERE id = ? AND student_id = ?");
        $wallet_check->bind_param("ii", $wallet_id, $student_id);
        $wallet_check->execute();
        $wallet_check->store_result();
        
        if ($wallet_check->num_rows === 0) {
            $_SESSION['error'] = "Invalid wallet";
            header("Location: wallet.php");
            exit();
        }
        
        // Get bank account details
        $account_stmt = $conn->prepare("
            SELECT * FROM student_bank_accounts 
            WHERE id = ? AND student_id = ?
        ");
        $account_stmt->bind_param("ii", $bank_account_id, $student_id);
        $account_stmt->execute();
        $account_result = $account_stmt->get_result();
        $bank_account = $account_result->fetch_assoc();
        
        if (!$bank_account) {
            $_SESSION['error'] = "Invalid bank account";
            header("Location: wallet.php");
            exit();
        }
        
        $conn->begin_transaction();
        
        try {
            // Create transaction record
            $reference = 'BANK-' . strtoupper(uniqid());
            $transaction_stmt = $conn->prepare("
                INSERT INTO wallet_transactions (
                    wallet_id, amount, transaction_type, reference, payment_method, status, description
                ) VALUES (?, ?, 'deposit', ?, 'bank_transfer', 'pending', ?)
            ");
            $description = "Deposit from " . $bank_account['bank_name'] . " (****" . substr($bank_account['account_number'], -4) . ")";
            $transaction_stmt->bind_param(
                "idss", 
                $wallet_id, 
                $amount, 
                $reference, 
                $description
            );
            $transaction_stmt->execute();
            
            $conn->commit();
            
            $_SESSION['success'] = "Bank transfer initiated. Please complete the transfer using the provided instructions.";
            $_SESSION['bank_transfer_reference'] = $reference;
            header("Location: bank_transfer_instructions.php?reference=" . $reference);
            exit();
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['error'] = "Error processing deposit: " . $e->getMessage();
            header("Location: wallet.php");
            exit();
        }
    }
} else {
    header("Location: wallet.php");
    exit();
}