<?php
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    $action = $_GET['action'] ?? '';

    if ($action === 'request') {
        $vendorEmail = $data['vendorEmail'] ?? '';
        $amount = (float)($data['amount'] ?? 0);

        if (!$vendorEmail || $amount <= 0) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid withdrawal request']);
            exit;
        }

        $pdo->beginTransaction();
        try {
            // Check balance
            $stmt = $pdo->prepare("SELECT id, wallet_balance FROM vendors WHERE contactEmail = ?");
            $stmt->execute([$vendorEmail]);
            $vendor = $stmt->fetch();

            if (!$vendor) {
                throw new Exception("Vendor not found");
            }

            if ($vendor['wallet_balance'] < $amount) {
                throw new Exception("Insufficient balance");
            }

            // Deduct balance
            $pdo->prepare("UPDATE vendors SET wallet_balance = wallet_balance - ? WHERE id = ?")->execute([$amount, $vendor['id']]);

            // Create record
            $pdo->prepare("INSERT INTO withdrawals (vendor_id, amount, status, requestedAt) VALUES (?, ?, 'pending', ?)")
                ->execute([$vendor['id'], $amount, time()]);

            $pdo->commit();
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            $pdo->rollBack();
            http_response_code(400);
            echo json_encode(['error' => $e->getMessage()]);
        }
    } else if ($action === 'approve') {
        $id = $data['id'] ?? 0;
        try {
            $pdo->prepare("UPDATE withdrawals SET status = 'approved', processedAt = ? WHERE id = ?")
                ->execute([time(), $id]);
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    } else if ($action === 'reject') {
        $id = $data['id'] ?? 0;
        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare("SELECT * FROM withdrawals WHERE id = ?");
            $stmt->execute([$id]);
            $withdrawal = $stmt->fetch();

            if ($withdrawal && $withdrawal['status'] === 'pending') {
                // Refund wallet
                $pdo->prepare("UPDATE vendors SET wallet_balance = wallet_balance + ? WHERE id = ?")
                    ->execute([$withdrawal['amount'], $withdrawal['vendor_id']]);
                
                $pdo->prepare("UPDATE withdrawals SET status = 'rejected', processedAt = ? WHERE id = ?")
                    ->execute([time(), $id]);
            }
            $pdo->commit();
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            $pdo->rollBack();
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }
} else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $vendorEmail = $_GET['vendorEmail'] ?? '';
        
        if ($vendorEmail) {
            // Get withdrawals for a specific vendor
            $stmt = $pdo->prepare("SELECT w.* FROM withdrawals w JOIN vendors v ON w.vendor_id = v.id WHERE v.contactEmail = ? ORDER BY w.requestedAt DESC");
            $stmt->execute([$vendorEmail]);
            $withdrawals = $stmt->fetchAll();
            echo json_encode($withdrawals);
        } else {
            // Get all withdrawals for admin
            $stmt = $pdo->query("SELECT w.*, v.businessName, v.bankName, v.accountName, v.accountNumber, v.contactEmail FROM withdrawals w JOIN vendors v ON w.vendor_id = v.id ORDER BY w.requestedAt DESC");
            $withdrawals = $stmt->fetchAll();
            echo json_encode($withdrawals);
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}
?>
