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

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

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

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

if (empty($reason)) {
    flash('message', 'Rejection reason is required', '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');
    }
    
    // Reject vendor
    $result = $vendor_model->updateApprovalStatus($vendor_id, 'rejected', Auth::id(), $reason);
    
    if ($result) {
        // Send notification to vendor
        $notification_service = new NotificationService();
        $notification_service->notifyVendorRejected($vendor_id, $reason);
        
        flash('message', 'Vendor rejected successfully!', 'success');
    } else {
        flash('message', 'Failed to reject vendor', 'danger');
    }
    
} catch (Exception $e) {
    log_message("Vendor rejection error: " . $e->getMessage(), 'error');
    flash('message', 'An error occurred while rejecting vendor', 'danger');
}

redirect('vendors.php');