<?php
// NOMBRE: db/staff-actions.php
ob_start();
ob_clean();
require_once '../core/api.php';

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

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    // --- BORRAR ACADEMIA O DOCUMENTOS ---
    if ($action === 'delete_academy') {
        $id = (int)$input['id'];
        $type = $input['type']; 

        if ($type === 'video') {
            // Borrar video (solo registro DB)
            $pdo->prepare("DELETE FROM staff_academy WHERE id = ?")->execute([$id]);
        } 
        elseif ($type === 'doc') {
            // 1. OBTENER LA RUTA DEL ARCHIVO ANTES DE BORRARLO
            $stmt = $pdo->prepare("SELECT file_path FROM staff_documents WHERE id = ?");
            $stmt->execute([$id]);
            $filePath = $stmt->fetchColumn();

            // 2. BORRAR REGISTRO DE LA BASE DE DATOS
            $pdo->prepare("DELETE FROM staff_documents WHERE id = ?")->execute([$id]);

            // 3. BORRAR ARCHIVO FÍSICO DEL SERVIDOR
            if ($filePath) {
                $fullPath = __DIR__ . '/../' . $filePath;
                
                if (file_exists($fullPath)) {
                    if (!unlink($fullPath)) {
                        error_log("No se pudo borrar el archivo físico: " . $fullPath);
                    }
                }
            }
        }
        echo json_encode(['success' => true, 'message' => 'Elemento eliminado correctamente']);
    }
    
    // --- ASIGNACIONES (staff_id en clients o routes) ---
    elseif ($action === 'assign') {
        $table = ($input['type'] === 'client') ? 'clients' : 'routes';
        $stmt = $pdo->prepare("UPDATE $table SET staff_id = ? WHERE id = ?");
        $stmt->execute([$input['staff_id'], $input['item_id']]);
        echo json_encode(['success' => true]);
    }
    
    elseif ($action === 'unassign') {
        $table = ($input['type'] === 'client') ? 'clients' : 'routes';
        $stmt = $pdo->prepare("UPDATE $table SET staff_id = NULL WHERE id = ?");
        $stmt->execute([$input['item_id']]);
        echo json_encode(['success' => true]);
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>