<?php
// db/live-business-actions.php

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

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Sesión expirada. Recarga la página.']);
    exit;
}

try {
    require_once __DIR__ . '/../core/api.php';
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error de conexión: ' . $e->getMessage()]);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';
$id = filter_var($input['id'] ?? 0, FILTER_VALIDATE_INT);
$user_id = $_SESSION['user_id'];

if (!$id || $id <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID inválido.']);
    exit;
}

try {
    $pdo->beginTransaction();
    $msg = '';
    $rowsAffected = 0;

    if ($action === 'approve_appointment') {
       $stmt = $pdo->prepare("UPDATE unique_appointments SET status = 'confirmed' WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user_id]);
        $rowsAffected = $stmt->rowCount();
        $msg = 'Cita Aprobada Correctamente.';
    } 
    elseif ($action === 'reject_appointment') {
        $stmt = $pdo->prepare("UPDATE unique_appointments SET status = 'cancelled' WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user_id]);
        $rowsAffected = $stmt->rowCount();
        $msg = 'Cita Rechazada.';
    }
    
    elseif ($action === 'approve_lead') {
        $stmt = $pdo->prepare("UPDATE leads SET status = 'Nuevo', updated_at = NOW() WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user_id]);
        $rowsAffected = $stmt->rowCount();
        $msg = 'Prospecto Aprobado.';
    }
    elseif ($action === 'contact_lead') {
        $stmt = $pdo->prepare("UPDATE leads SET status = 'Contactado', updated_at = NOW() WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user_id]);
        $rowsAffected = $stmt->rowCount();
        $msg = 'Prospecto Marcado como Contactado.';
    }
    elseif ($action === 'dismiss_lead') {
        $stmt = $pdo->prepare("UPDATE leads SET status = 'Lead Archivado', updated_at = NOW() WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user_id]);
        $rowsAffected = $stmt->rowCount();
        $msg = 'Prospecto Archivado.';
    }
    
    elseif ($action === 'resolve_complaint') {
        $stmt = $pdo->prepare("UPDATE complaints SET status = 'Resuelto', updated_at = NOW() WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user_id]);
        $rowsAffected = $stmt->rowCount();
        $msg = 'Queja Resuelta.';
    }
    else {
        throw new Exception('Acción desconocida.');
    }

    if ($rowsAffected === 0) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'No se encontró el registro o no tienes permiso.']);
        exit;
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => $msg]);

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['success' => false, 'message' => 'Error del Sistema: ' . $e->getMessage()]);
}
?>