<?php
/**
 * API: Update Dispute Status - FIXED FOR ACTUAL DATABASE
 * File: api/update-dispute-status.php
 */

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

header('Content-Type: application/json');

if (!Auth::check()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
    exit;
}

$dispute_id = $_POST['dispute_id'] ?? 0;
$new_status = $_POST['status'] ?? '';

try {
    // Use your actual database status values
    $allowed_statuses = ['open', 'under_review', 'resolved', 'closed'];
    
    if (!in_array($new_status, $allowed_statuses)) {
        throw new Exception("Invalid status");
    }
    
    $db = Database::getInstance();
    $user_id = Auth::getUserId();
    
    // Verify user can update this dispute
    $dispute_sql = "SELECT d.*, 
                    o.vendor_id,
                    o.customer_id,
                    v.user_id as vendor_user_id,
                    c.user_id as customer_user_id
                    FROM disputes d
                    JOIN orders o ON d.order_id = o.id
                    LEFT JOIN vendors v ON o.vendor_id = v.id
                    LEFT JOIN customers c ON o.customer_id = c.id
                    WHERE d.id = ?";
    
    $dispute = $db->fetch($dispute_sql, [$dispute_id]);
    
    if (!$dispute) {
        throw new Exception("Dispute not found");
    }
    
    // Only vendor or admin can update status
    $is_vendor = $dispute['vendor_user_id'] == $user_id;
    $is_admin = Auth::isAdmin();
    
    if (!$is_vendor && !$is_admin) {
        throw new Exception("Unauthorized");
    }
    
    // Update status
    $db->execute(
        "UPDATE disputes SET status = ?, updated_at = NOW() WHERE id = ?",
        [$new_status, $dispute_id]
    );
    
    // If resolved or closed, update order's dispute flag
    if (in_array($new_status, ['resolved', 'closed'])) {
        $db->execute(
            "UPDATE orders SET has_active_dispute = 0 WHERE id = ?",
            [$dispute['order_id']]
        );
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Dispute status updated successfully'
    ]);
    
} catch (Exception $e) {
    error_log("Update dispute status error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}