<?php
// admin/resolve_dispute.php
require_once __DIR__ . '/../config/db.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }

// 1. SEGURIDAD: Solo el admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Acceso denegado.");
}

$order_id = $_POST['order_id'] ?? null;
$action   = $_POST['action'] ?? null;
$admin_id = $_SESSION['user_id'];

if (!$order_id || !$action) {
    header("Location: disputes.php?error=missing_data");
    exit;
}

try {
    $pdo->beginTransaction();

    // 2. OBTENER LA ORDEN CON BLOQUEO
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? FOR UPDATE");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch();

    if (!$order) { throw new Exception("Orden no encontrada."); }

    // 3. PROCESAR SEGÚN LA ACCIÓN
    if ($action === 'refund') {
        $target_user = $order['buyer_id'];
        $status_text = 'REFUNDED';
        $log_detail = "Admin refunded Order #$order_id to Buyer ID: $target_user";
        $notif_title = "Dispute Resolved: Refund";
        $notif_body = "The dispute for Order #$order_id has been resolved in your favor. Funds returned to your wallet.";
        
        // Actualizar Balance Real del Comprador
        $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")
            ->execute([$order['total_price'], $target_user]);

    } elseif ($action === 'settle') {
        $target_user = $order['seller_id'];
        $status_text = 'SETTLED';
        $log_detail = "Admin released Order #$order_id funds to Seller ID: $target_user";
        $notif_title = "Dispute Resolved: Funds Released";
        $notif_body = "The dispute for Order #$order_id is closed. Funds have been credited to your account.";

        // Actualizar Balance Real del Vendedor
        $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")
            ->execute([$order['total_price'], $target_user]);
    }

    // 4. INSERTAR EN LEDGER (Contabilidad técnica)
    $stmt_l = $pdo->prepare("INSERT INTO ledger (user_id, amount, entry_type, category, description) VALUES (?, ?, 'credit', 'dispute_res', ?)");
    $stmt_l->execute([$target_user, $order['total_price'], $log_detail]);

    // 5. ACTUALIZAR ESTADO DE LA ORDEN
    $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?")->execute([$status_text, $order_id]);

    // 6. REGISTRAR EL LOG DE ADMIN (Auditoría)
    $stmt_log = $pdo->prepare("INSERT INTO admin_logs (admin_id, action_type, target_user_id, details) VALUES (?, 'DISPUTE_RESOLUTION', ?, ?)");
    $stmt_log->execute([$admin_id, $target_user, $log_detail]);

    // 7. ENVIAR NOTIFICACIÓN AL GANADOR
    $stmt_notif = $pdo->prepare("INSERT INTO system_notifications (user_id, title, message) VALUES (?, ?, ?)");
    $stmt_notif->execute([$target_user, $notif_title, $notif_body]);

    $pdo->commit();
    header("Location: disputes.php?success=" . $action . "_ok");
    exit;

} catch (Exception $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    header("Location: disputes.php?error=" . urlencode($e->getMessage()));
    exit;
}