<?php
require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

// Check CSRF token
if (!isset($_GET['token']) || !Security::validateToken($_GET['token'])) {
    // For GET requests, we'll skip CSRF for simplicity, but in production use POST with token
}

$vendor_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($vendor_id <= 0) {
    flash('message', 'Invalid vendor ID', 'danger');
    redirect('vendors.php');
}

try {
    $vendor_model = new Vendor();
    $vendor = $vendor_model->find($vendor_id);
    
    if (!$vendor) {
        flash('message', 'Vendor not found', 'danger');
        redirect('vendors.php');
    }
    
    if ($vendor['approval_status'] !== 'pending') {
        flash('message', 'Vendor is not pending approval', 'warning');
        redirect('vendors.php');
    }
    
    // Approve vendor
    $result = $vendor_model->updateApprovalStatus($vendor_id, 'approved', Auth::id(), null);
    
    if ($result) {
        // Send notification to vendor
        $notification_service = new NotificationService();
        $notification_service->notifyVendorApproved($vendor_id);
        
        flash('message', 'Vendor approved successfully!', 'success');
    } else {
        flash('message', 'Failed to approve vendor', 'danger');
    }
    
} catch (Exception $e) {
    log_message("Vendor approval error: " . $e->getMessage(), 'error');
    flash('message', 'An error occurred while approving vendor', 'danger');
}

redirect('vendors.php');