<?php
require_once 'db.php';

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

    if ($action === 'apply') {
        $id = uniqid('v_');
        $stmt = $pdo->prepare("INSERT INTO vendors (
            id, status, appliedAt, storeSlug, businessName, businessType, category, rcNumber, taxId, 
            contactName, contactEmail, contactPhone, altPhone, address, city, state, country, 
            website, productInfo, bankName, accountName, accountNumber
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $id, 'pending', time(), $data['businessName'] ?? '', $data['businessName'], 
            $data['businessType'], $data['category'], $data['rcNumber'] ?? '', $data['taxId'] ?? '',
            $data['contactName'], $data['contactEmail'], $data['contactPhone'], $data['altPhone'] ?? '',
            $data['address'], $data['city'], $data['state'], $data['country'] ?? 'Nigeria',
            $data['website'] ?? '', $data['productInfo'], $data['bankName'], $data['accountName'], $data['accountNumber']
        ]);
        echo json_encode(['success' => true, 'id' => $id]);
    } else if ($action === 'approve') {
        // Needs admin auth check ideally
        $id = $data['id'];
        $stmt = $pdo->prepare("UPDATE vendors SET status = 'approved' WHERE id = ?");
        $stmt->execute([$id]);
        echo json_encode(['success' => true]);
    } else if ($action === 'delete') {
        $id = $data['id'];
        $stmt = $pdo->prepare("DELETE FROM vendors WHERE id = ?");
        $stmt->execute([$id]);
        echo json_encode(['success' => true]);
    } else if ($action === 'verify') {
        $id = $data['id'];
        $stmt = $pdo->prepare("UPDATE vendors SET is_verified = TRUE WHERE id = ?");
        $stmt->execute([$id]);
        echo json_encode(['success' => true]);
    } else if ($action === 'edit_profile') {
        $id = $data['id'];
        $stmt = $pdo->prepare("UPDATE vendors SET banner = ?, logo = ? WHERE id = ?");
        $stmt->execute([
            $data['banner'] ?? null,
            $data['logo'] ?? null,
            $id
        ]);
        echo json_encode(['success' => true]);
    }
}
?>
