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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die(json_encode(['success' => false, 'message' => 'Invalid request method']));
}

if (!isset($_SESSION['user_id'])) {
    die(json_encode(['success' => false, 'message' => 'Not authenticated']));
}

$student_id = $_SESSION['user_id'];
$wallet_id = $_POST['wallet_id'] ?? 0;
$amount = floatval($_POST['amount'] ?? 0);
$bank_account_id = $_POST['bank_account_id'] ?? 0;
$transaction_pin = $_POST['transaction_pin'] ?? '';

// Validate inputs
if ($amount < 100) {
    die(json_encode(['success' => false, 'message' => 'Minimum withdrawal is ₦100']));
}

if (empty($bank_account_id)) {
    die(json_encode(['success' => false, 'message' => 'Bank account is required']));
}

if (strlen($transaction_pin) !== 4 || !ctype_digit($transaction_pin)) {
    die(json_encode(['success' => false, 'message' => 'Invalid transaction PIN']));
}

// Verify transaction PIN
$pin_stmt = $conn->prepare("SELECT pin_hash FROM wallet_pins WHERE student_id = ?");
$pin_stmt->bind_param("i", $student_id);
$pin_stmt->execute();
$pin_result = $pin_stmt->get_result();

if ($pin_result->num_rows === 0) {
    die(json_encode(['success' => false, 'message' => 'Transaction PIN not set']));
}

$pin_data = $pin_result->fetch_assoc();
if (!password_verify($transaction_pin, $pin_data['pin_hash'])) {
    die(json_encode(['success' => false, 'message' => 'Incorrect transaction PIN']));
}

// Check wallet balance
$wallet_stmt = $conn->prepare("SELECT balance FROM student_wallets WHERE id = ? AND student_id = ?");
$wallet_stmt->bind_param("ii", $wallet_id, $student_id);
$wallet_stmt->execute();
$wallet_result = $wallet_stmt->get_result();

if ($wallet_result->num_rows === 0) {
    die(json_encode(['success' => false, 'message' => 'Wallet not found']));
}

$wallet = $wallet_result->fetch_assoc();
if ($wallet['balance'] < $amount) {
    die(json_encode(['success' => false, 'message' => 'Insufficient balance']));
}

// Get bank account details
$bank_stmt = $conn->prepare("SELECT * FROM student_bank_accounts WHERE id = ? AND student_id = ?");
$bank_stmt->bind_param("ii", $bank_account_id, $student_id);
$bank_stmt->execute();
$bank_result = $bank_stmt->get_result();

if ($bank_result->num_rows === 0) {
    die(json_encode(['success' => false, 'message' => 'Bank account not found']));
}

$bank_account = $bank_result->fetch_assoc();

// Start transaction
$conn->begin_transaction();

try {
    // Deduct from wallet
    $update_stmt = $conn->prepare("UPDATE student_wallets SET balance = balance - ? WHERE id = ?");
    $update_stmt->bind_param("di", $amount, $wallet_id);
    $update_stmt->execute();
    
    if ($update_stmt->affected_rows === 0) {
        throw new Exception('Failed to update wallet balance');
    }
    
    // Create withdrawal transaction
    $reference = 'WDR' . time() . mt_rand(1000, 9999);
    $description = "Withdrawal to " . $bank_account['bank_name'] . " (****" . substr($bank_account['account_number'], -4) . ")";
    
    $transaction_stmt = $conn->prepare("
        INSERT INTO wallet_transactions (
            wallet_id, 
            bank_account_id,
            amount, 
            transaction_type, 
            description, 
            status, 
            reference
        ) VALUES (?, ?, ?, 'withdrawal', ?, 'pending', ?)
    ");
    $transaction_stmt->bind_param("iidss", $wallet_id, $bank_account_id, $amount, $description, $reference);
    $transaction_stmt->execute();
    
    $transaction_id = $conn->insert_id;
    
    // Here you would typically initiate the bank transfer via Paystack/SmartPay API
    // This is a placeholder - implement according to your payment processor's API
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Withdrawal request submitted successfully',
        'transaction_id' => $transaction_id
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Withdrawal failed: ' . $e->getMessage()
    ]);
}
?>