<?php
/**
 * VENDOR REVIEW REPLY HANDLER
 * File: vendor/review-reply.php
 * Handle vendor replies to customer reviews
 */

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

// Require vendor authentication
Auth::requireVendor();

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    flash('error', 'Invalid request method', 'danger');
    redirect('items.php');
}

// Validate CSRF token
if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
    flash('error', 'Invalid security token', 'danger');
    redirect('items.php');
}

// Get and validate review ID
$review_id = isset($_POST['review_id']) ? (int)$_POST['review_id'] : 0;
$vendor_reply = trim($_POST['vendor_reply'] ?? '');

if (!$review_id || empty($vendor_reply)) {
    flash('error', 'Review ID and reply are required', 'danger');
    redirect('items.php');
}

// Initialize database
$db = Database::getInstance();
$vendor = new Vendor();

// Get vendor details
$vendor_id = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);

if (!$vendor_data) {
    flash('error', 'Vendor profile not found', 'danger');
    redirect('profile.php');
}

// Verify that the review belongs to one of the vendor's items
$review_sql = "SELECT r.*, i.vendor_id, i.title as item_title
               FROM reviews r
               JOIN items i ON r.item_id = i.id
               WHERE r.id = ? AND i.vendor_id = ?";
$review = $db->fetch($review_sql, [$review_id, $vendor_data['id']]);

if (!$review) {
    flash('error', 'Review not found or you do not have permission to reply', 'danger');
    redirect('items.php');
}

// Check if already replied
if (!empty($review['vendor_reply'])) {
    flash('error', 'You have already replied to this review', 'warning');
    redirect('item-details.php?id=' . $review['item_id']);
}

try {
    // Update review with vendor reply
    $update_sql = "UPDATE reviews 
                   SET vendor_reply = ?, 
                       vendor_replied_at = NOW(),
                       updated_at = NOW()
                   WHERE id = ?";
    
    $result = $db->execute($update_sql, [$vendor_reply, $review_id]);
    
    if ($result) {
        // Send notification to customer (optional - if you have notification system)
        // $notification = new NotificationService();
        // $notification->send(
        //     $review['customer_id'],
        //     'Vendor Replied to Your Review',
        //     "The vendor has replied to your review for '{$review['item_title']}'",
        //     'info',
        //     'customer'
        // );
        
        flash('success', 'Reply submitted successfully!', 'success');
        
        // Log the action
        log_message("Vendor {$vendor_data['business_name']} replied to review #{$review_id}", 'info');
    } else {
        flash('error', 'Failed to submit reply. Please try again.', 'danger');
    }
    
} catch (Exception $e) {
    log_message("Review reply error: " . $e->getMessage(), 'error');
    flash('error', 'An error occurred while submitting your reply', 'danger');
}

// Redirect back to item details
redirect('item-details.php?id=' . $review['item_id']);
?>